A reference namespace is required to use the Regex class: using System.Text.RegularExpressions;
Implementing validation with the Regex class
Example 1: Commented code has the same effect, but one is a static method and one is an instance method
var Source = "Liu Bei Guan Yu Zhang Sun Quan";
Regex regex = new Regex ("Sun Quan");
if (regex. IsMatch (source))
//{
Console.WriteLine ("The string contains a sensitive word: Sun Quan! ");
//}
if (Regex.IsMatch (Source, "Sun Quan"))
{
Console.WriteLine ("The string contains a sensitive word: Sun Quan! ");
}
Console.ReadLine ();
Example 2: Using a constructor with two parameters, the second parameter indicates ignoring case, very common
var Source = "123abc345def";
Regex regex = new Regex ("Def", Regexoptions.ignorecase);
if (regex. IsMatch (source))
{
Console.WriteLine ("The string contains a sensitive word: def! ");
}
Console.ReadLine ();
Replace with the Regex class
Example 1: Simple case
var Source = "123abc456abc789";
Static methods
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 ();
Results:
Original string: 123abc456abc789
Replaced string: 123|456|789
Example 2: Replace the matching option with the HTML code, we used the MatchEvaluator delegate
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
C # Regex class usage