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: