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]

Proper case match

   
 

using System;
using System.Text.RegularExpressions;


public class RXProperCaseApp {
    static void Main(string[] args) {
        string s = "the qUEEn wAs in HER parLOr";
        s = s.ToLower();
        string e = @"w+|W+";
        string sProper = "";

        foreach (Match m in Regex.Matches(s, e)) {
            sProper += char.ToUpper(m.Value[0])
                + m.Value.Substring(1, m.Length - 1);
        }
        Console.WriteLine("ProperCase:	{0}", sProper);
    }
}

    


Leading space

   
 

using System;
using System.Text.RegularExpressions;


class RXmodifyingApp {
    static void Main(string[] args) {
        string s = "     leading";
        string e = @"^s+";
        Regex rx = new Regex(e);
        string r = rx.Replace(s, "");
        Console.WriteLine("Strip leading space: {0}", r);
    }
}

    


Define groups 'ing', 'in', 'n'

using System;
using System.Text.RegularExpressions;

class GroupingApp {
static void Main(string[] args) {
Regex r = new Regex(“(i(n))g”);
Match m = r.Match(“Matching”);
GroupCollection gc = m.Groups;
Console.WriteLine(“Found {0} Groups”, gc.Count);
for (int i = 0; i < gc.Count; i++) { Group g = gc[i]; Console.WriteLine("Found '{0}' at position {1}",g.Value, g.Index); } } } [/csharp]