Use regular to replace word


   


using System;
using System.Text.RegularExpressions;

class RegexSubstitution
{
   public static void Main()
   {
      string testString1 = "a b c stars *****";
      Regex testRegex1 = new Regex( @"d" );

      Console.WriteLine( "Original string: " + testString1 );
      Console.WriteLine( "Every word replaced by "word": " + Regex.Replace( testString1, @"w+", "word" ) );
      
   }
}

           
          


Use regular to replace strings


   


using System;
using System.Text.RegularExpressions;

class RegexSubstitution
{
   public static void Main()
   {
      string testString1 = " stars *****";
      Regex testRegex1 = new Regex( @"d" );

      Console.WriteLine( "Original string: " + testString1 );
      testString1 = Regex.Replace( testString1, "stars", "carets" );
      Console.WriteLine( ""carets" substituted for "stars": " + testString1 );
      
   }
}

           
          


Use regular expression to replace chars


   

using System;
using System.Text.RegularExpressions;

class RegexSubstitution
{
   public static void Main()
   {
      string testString1 = " stars *****";
      Regex testRegex1 = new Regex( @"d" );

      Console.WriteLine( "Original string: " + testString1 );
      testString1 = Regex.Replace( testString1, @"*", "^" );
      Console.WriteLine( "^ substituted for *: " + testString1 );
      
   }
}


           
          


IP address

using System;
using System.Text.RegularExpressions;

class RXassemblyApp {
static void Main(string[] args) {
string s = “123.45.67.89”;
string e =
@”([01]?dd?|2[0-4]d|25[0-5]).” +
@”([01]?dd?|2[0-4]d|25[0-5]).” +
@”([01]?dd?|2[0-4]d|25[0-5]).” +
@”([01]?dd?|2[0-4]d|25[0-5])”;
Match m = Regex.Match(s, e);
Console.WriteLine(“IP Address: {0}”, m);
for (int i = 1; i < m.Groups.Count; i++) Console.WriteLine( " Group{0}={1}", i, m.Groups[i]); } } [/csharp]

Use | to combine different case

using System;
using System.Text.RegularExpressions;

class RXOptionsApp {
static void Main(string[] args) {
Regex r = new Regex(“in|In|IN|iN”);
string s = “The KING Was In His Counting House”;
MatchCollection mc = r.Matches(s);
for (int i = 0; i < mc.Count; i++) { Console.WriteLine("Found '{0}' at position {1}",mc[i].Value, mc[i].Index); } } } [/csharp]