using System; using System.Text.RegularExpressions; class RegexSubstitution { public static void Main() { string testString1 = "1, 2, 3, 4, 5, 6, 7, 8"; Regex testRegex1 = new Regex( @"d" ); Console.WriteLine( "Original string: " + testString1 ); String[] result = Regex.Split( testString1, @",s" ); foreach ( string resultString in result ) Console.WriteLine(""" + resultString + "", "); } }
Use regular expression to replace first 3 digits
using System; using System.Text.RegularExpressions; class RegexSubstitution { public static void Main() { string testString1 = "1, 2, 3, 4, 5, 6, 7, 8"; Regex testRegex1 = new Regex( @"d" ); Console.WriteLine( "Original string: " + testString1 ); Console.WriteLine( "Replace first 3 digits by "digit": " + testRegex1.Replace( testString1, "digit", 3 ) ); } }
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 ); } }
Multiple spaces, using ” “
using System; using System.Text.RegularExpressions; public class MainClass { public static void Main() { string u = "Once Upon A Time In America"; Regex p = new Regex(" "); foreach (string ss in p.Split(u)) { Console.WriteLine(ss); } } }
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]