C # RegEx class usage

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.