C # using regular Expressions __ regular expressions

Source: Internet
Author: User

Statement: This article only shows how C # use regular expressions, is a little note of their own learning, not in-depth introduction


First, you need to refer to the library of the regular expression.

Using System.Text.RegularExpressions;

Then you need to be clear about what kind of text (source text) you want to get the information you want (target text)

For example: You need from "my contact, qq274743199, my phone xxxx," The sentence text, extract QQ number

We refine the information as follows:

Source text:

String teststring = "My contact way, qq274743199, my phone xxxx";

Target text:

274743199


At this point, you need to define a regular expression to match your target text:

string zzstring = null;

zzstring = @ "QQ (\d+),";

Note: Of course the direct use here (\d+) is also possible, but in order to improve accuracy, you can add the same key word or format, reduce the matching range, improve the robustness of the matching formula


Okay, we can start a match.

MatchCollection mc=regex.matches (teststring, zzstring);
Console.WriteLine (MC. Count);

if (MC. Count > 0)
{
Console.WriteLine ("Matching success");
Console.WriteLine ("Match result: {0}", Mc[0]. Groups[0]. Value);//Match result
QQ = Mc[0]. GROUPS[1]. Value;
Console.WriteLine ("Match child result: {0}", QQ);//First subexpression
}
Else
{
Console.WriteLine ("Match succeeded, but result is empty");
}


Additional knowledge points, setting match pattern

MatchCollection mc = regex.matches (teststring, zzstring,regexoptions.ignorecase| Regexoptions.multiline);




Complete code:





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.