To use the Regex class, you need to reference the namespace: using System.Text.RegularExpressions;
Validation is implemented using the Regex class
Example 1: The annotated code does the same thing, but one is a static method and the other is an instance method
var source = "Liu Bei, Guan Yu, Zhang Fei, Sun Quan"; Regex regex = new Regex("Sun Quan"); //if (regex. IsMatch(source)) //{ Console.WriteLine("The string contains sensitive words: Sun Quan!) ); //} if (Regex.IsMatch(source, "Sun Quan"))
{ Console.WriteLine("The string contains sensitive words: Sun Quan!) );
} Console.ReadLine();
Example 2: Using a constructor with two parameters, the second parameter indicates ignoring case and is commonly used
var source = "123abc345DEf"; Regex regex = new Regex("def",RegexOptions.IgnoreCase); if (regex. IsMatch(source))
{ Console.WriteLine("String contains sensitive words: def!) );
} Console.ReadLine();
Use the Regex class to replace it
Example 1: Simple situation
var source = "123abc456ABC789"; Static method //var newSource=Regex.Replace(source,"abc","|",RegexOptions.IgnoreCase); Instance method Regex regex = new Regex("abc", RegexOptions.IgnoreCase); var newSource = regex. Replace(source, "|"); Console.WriteLine("Original string:"+source); Console.WriteLine("Replaced string:"+newSource); Console.ReadLine();
Outcome:
Original string: 123abc456ABC789
Replaced string: 123|456|789
Example 2: Replacing the matched options with html code, we used the MatchEvaluator delegation
var source = "123abc456ABCD789"; Regex regex = new Regex("[A-Z]{3}", RegexOptions.IgnoreCase); var newSource = regex. Replace(source,new MatchEvaluator(OutPutMatch)); Console.WriteLine("Original string:"+source); Console.WriteLine("Replaced string:"+newSource); Console.ReadLine();
private static string OutPutMatch(Match match)
{ return "<b>" +match. Value+ "</b>";
}
Output:
Original string: 123abc456ABCD789
Replaced string: 123<b>abc</b>456<b>ABC</b>D789 |