Replacing and Splitting Text

The RegEx.Replace method works like string.Replace, except that it uses a regular expression.


using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main(string[] args)
    {
       string find = @"\bis\b"; 
       string replace = "are"; 
       Console.WriteLine (Regex.Replace ("This is a test", find, replace)); 

    }
}

The output:


This are a test

The replacement string can reference the original match with the $0 substitution construct.

The following example wraps numbers within a string in angle brackets:

 
using System;
using System.Text.RegularExpressions;


class Program
{
    static void Main(string[] args)
    {

       string text = "10, 20, 30 and 40"; 
       Console.WriteLine (Regex.Replace (text, @"\d+", @"<$0>")); 

    }
}
  

The output:

<10>, <20>, <30> and <40>
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.