C # Regex class usage

Source: Internet
Author: User

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

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.