To use the RegEx class, you must reference the namespace: using system. Text. regularexpressions;
Verification using the RegEx class
Example 1: AnnotatedCodeThe role is the same, but one is static method and the other is instance method.
VaR source = "Liu Bei Guan Yu Zhang Fei Sun Quan ";
// 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: Use a constructor with two parameters. The second parameter indicates case-insensitive and is very common.
VaR source = "123abc345def ";
RegEx = new RegEx ("def", regexoptions. ignorecase );
If (RegEx. ismatch (source ))
{
Console. writeline ("the string contains the sensitive word def! ");
}
Console. Readline ();
Replace with the RegEx class
Example 1: simple
VaR source = "123abc456abc789 ";
// Static method
// Var newsource =RegEx. Replace (source, "ABC", "|", regexoptions. ignorecase );
// Instance method
RegEx = new RegEx ("ABC", regexoptions. ignorecase );
VaR newsource =RegEx. Replace (source, "| ");
Console. writeline ("original string:" + source );
Console. writeline ("replaced string:" + newsource );
Console. Readline ();
Result:
Original string: 123abc456abc789
Replaced string: 123 | 456 | 789
Example 2: replace the matched options with the HTML code. We use the matchevaluator delegate.
VaR source = "123abc456abcd789 ";
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)
{
Return "<B>" + match. Value + "</B> ";
}
Output:
Original string: 123abc456abcd789
Replaced string: 123 <B> ABC </B> 456 <B> ABC </B> d789