Regular expression (Regex class)

Source: Internet
Author: User

Namespaces:
System.Text.RegularExpressions

Initializing the Regex class
Regex regex = new Regex (regular expression, Regexoptions.ignorecase | Regexoptions.multiline);
IgnoreCase ignores case when matching, multiline adjusts the meaning of ^ and $ to match the beginning and end of a row.

Match () and Matches () methods:
Match () matches a result; matches () matches multiple results
Example: Fetching a row of consecutive digits from a string
Regex regex = new Regex (@ "/d+");
Match m = regex. Match ("bei2008jing@163.com");
Console.WriteLine (M.value.tostring ());
Output results:
2008

Extract all numbers from a section of string
Regex regex = new Regex (@ "/d+");
MatchCollection ms = Regex. Matches ("bei2008jing@163.com");
foreach (Match m in ms)
{
Console.WriteLine (M.value.tostring ());
}
Output results
2008
163

Split () function:
Single character segmentation
String str = "11123332444";
string[] array = str. Split (' 2 ');
foreach (string s in array)
{
Console.WriteLine (s);
}
Output results:
111
333
444

Multi-string Segmentation:
1.string str = "11122223332222444";
string[] Arrray = str. Split (New char[4]{' 2 ', ' 2 ', ' 2 ', ' 2 '});
foreach (string s in array)
{
Console.WriteLine (s);
}
Output results:
111

333

444

2.string str = "11122223332222444";
string[] array = regex.split (str, "2222", regexoption.ignorecase);
Regex regex = new Regex ("2222");
string[] Array = regex. Split (str);
foreach (string s in array)
{
Console.WriteLine (s);
}
Output results:
111
333
444

Batch string substitution:
String str = "11122223332222444";
Regex regex = new Regex ("2222");
str = regex. Replace (str, "a");
str = regex.replace (str, "2222", "a");
Console.WriteLine (str);
Console.ReadLine ();

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.