Regular Expressions is a synthetic matching rule, various languages, such as Perl, .NET, and Java have their corresponding shared regular expression class libraries. In .NET, this class library is called Regex.
Simply put, Regex is a reference class that looks up the matching string from the character window. With Regex, programmers can easily extract data information they need from a segment of data. To give a simple example, let everyone have a probably understanding of Regex:
Regex regex = new regex (@ "/ d ");
Match m = regex.match ("Fox 9212Gold");
Console.writeline (M.Value.tostring ());
The result is clear that Regex finds the numeric string in the string "Fox 9212Gold", and the output is "9212".
After regex has a basic concept, I need to tell you a very good news, that is, regex can do so for us, he is a very powerful grammatical matching rule. Of course, there is still a bad news waiting for us, that is, the symptom rules of powerful features naturally require a large number of complex Keyword support, which also brings great difficulties for regex learning. Want to truly master the regular expression, not a few SAMPLEs can be disclosed and illustrated.
Create a regex object
There are three constructor of Regex, and the default constructor is not discussed here. In the other two constructors, a constructor receives a regular expression string as an incoming parameters, and the other is incorporated by the regular expression string and regexoptions. Such as:
Regex regex = New regex ("/ w $");
Regex regex = new regex ("/ s ", regexoptions.ignorecase | regexoptions.multiline;
Regexoptions can provide us with some special help, such as IgnoreCase, can be ignored by matching, Multiline can adjust ^ and $ meaning, change to match the beginning and end.
Above we constructed a regular expression, but we have not used it to do anything, immediately we can implement the operation of the string object by using several methods below.
Match string
Regex has two ways to acquire match match (), and matches (), which match one, match multiple results, respectively. Here, use Matches to show how to use Regex to get match strings and display it.
Public Static Void Showmatches (String Expression, Regexoptions Option, String MS)
{
Regex regex = new regex (Expression, Option);
Matchcollection matches = regex.matches (ms);
// show matches
Console.writeline ("------------------------------");
Console.writeline ("String: /" {0} / "{1} /" / r / n match result is: ",
MS, Expression);
FOREACH (Match M in matches)
{Console.WriteLine ("Match string is: /" {0} / ", length: {1}", m.value.tostring (), M.Value.Length
}
Console.writeline ("Match Count: {0}", Matches.count;
}
Method Matched is found by comparing the entry string and the regular expression, and the result is passed as a MatchCollection. In this way, as long as it is simple to traverse this Collection, you can get all the results very quickly.
Set of concepts
When you get such a string "The last score is: 19/24", you must have a regular expression, he is not only able to find a string such as Data1 / Data2, but also able to directly put Data1, Data2 as a separate The result is transmitted. Otherwise, you need to analyze the string of "19/24" to get the score of both parties. Obviously, the regular expression will not ignore this problem, so he adds the concept of the group. You can put the results of the search in different groups, and obtain the results of these groups, respectively, through group names or groups. For example, we can use @ "(/ d ) / (/ d ) as expressions. Let's take a look:
Regex Regex = New Regex (@ "(/ d ) / (/ d )");
Matchcollection matches = regex.matches (@ "The last score is: 19/24");
// show matches
Console.writeline ("------------------------------");
FOREACH (Match M in matches)
{
//Console.writeline ("match string is: / "{0} /", length: {1} ", // m.value.tostring (), M.Value.Length
FOREACH (String Name in Regex.getGroupNames ())
{
Console.writeLine ("/ R Capture Group /" {0} / "value is: /" {1} / ""
Name, M.Groups [name] .value);
}
}
Console.writeline ("Match Count: {0}", Matches.count;
Output:
----------------------------------
Capture Group "0" Value IS: "19/24"
Capture Group "1" Value IS: "19"
Capture Group "2" Value IS: "24"
Match Count: 1
Now it is clear, the regex object puts the result of the match in group 0. At the same time, the matching group information is also placed in the corresponding group. The name of the group is in the default, it is an integer from 1 to 1. 0 As a reserved name, it is specifically used to indicate the entire string of the match. Since there is a concept of "default", nature also means that the user can customize the name of the group. The method is very simple, plus:?
Capture Group "0" Value IS: "19/24"
Capture Group "Score1" Value IS: "19"
Capture Group "Score2" Value IS: "24"
Match Count: 1
Change to your own definition, haha! In the future test, we can see all the results more convenient, we do a little small adjustment to the showmatches () introduced earlier. In this way, if we include the definition of the group in the expression, we can also see all group information directly without modifying any code, and the adjustment method showmatchespro () is as follows:
Public Static Void Showmatchespro (String Expression, Regexoptions Option, String MS)
{
Regex regex = new regex (Expression, Option);
Matchcollection matches = regex.matches (ms);
// show matches
Console.writeline ("------------------------------");
Console.writeline ("String: /" {0} / "{1} /" / r / n match result is: ",
MS, Expression);
FOREACH (Match M in matches)
{FOREACH (String Name in Regex.getGroupNames ())
{
Console.writeline ("/ R Capture Group /" {0} / "value is: /" {1} / ",
Name, M.Groups [name] .value);
}
}
Console.writeline ("Match Count: {0}", Matches.count;
// show group name
Console.writeline ("Group name count {0}", regex.getgroupnames (). Length);
FOREACH (String Name in Regex.getGroupNames ())
{
Console.Writeline ("Group name: /" {0} / "" "" "
}
}
Replace string
Regex also provides a convenient matching result. In order to facilitate testing, we also write him into a method, the code is as follows:
Public Static String ReplaceMatch (String Expression, RegexOptions Option, String MS, String)
{
Regex regex = new regex (Expression, Option);
String result = regex.replace (ms, rep);
Console.writeline ("------------------------------");
Console.writeline ("String: /" {0} / ", expression: /" {1} / ", replace by: /" {2} / "",
MS, Expression, REP);
Console.writeline ("Replace Result String IS: /" {0} / ", Length: {1}",
Result.toString (), Result.Length);
Return Result;
}
Regex.Replace usually accepts two string as incubating, the first String is an input string. The second string is used to replace the matching string, which can contain some special strings to represent special conversions.
Special string replacement results
$ & Matched strings, you can use $ 0
$ 1, $ 2,... Match the corresponding group in the string, indicate with an index
$ {name} Match the corresponding group in the string, named name
$ 'String before matching position
String after $ 'matching position
$$ A '$' Character
$ _ Input string
$ Match the data in the last group in all groups of strings
Is it a very strange special string, a little dizzy? Well, then get two samples to see the result!
Sample1:
Replacematch (@ "/ d ", regexoptions.none, "FEF 12/21 DF 33/14 727/1", "<< $ & >>");
Output, all digital data is replaced with << Data >>:
----------------------------------
String: "Fef 12/21 DF 33/14 727/1", Expression: "/ D ", Replace By: "$ & >>"
Replace result string is: "Fef << 12 >> / << 21 >> DF << 33 >> / << 14 >> << 727 >> / << 1 >>",
Length: 50
Sample2:
Replacematch (@ "(/ d ) / (/ d )", RegexOptions.none, "Fef 12/21 DF 33/14 727/1", "$ "); output, all Data1 / Data2 matches data, Replaced with Data2:
----------------------------------
String: "Fef 12/21 DF 33/14 727/1", Expression: "(/ d ) / (/ d )", Replace By: "$ "
Replace Result String IS: "Fef 21 DF 14 1", Length: 16
How, Regex's work can be enriched! However, maybe your demand is not as simple as it is, for example, you have to double the Money in the middle of "I Have 200 Dollars", what should I do? I fainted, it seems that there is no ready-made thing. There is no relationship, regex has a better function. It allows you to define a conversion formula.
Using system.text.regularExpressions;
Class RegularExpressions
{
Static String Captext (Match M)
{
// Get the match string.
String x = m.toString ();
// Double this value
String result = (int.Parse (x) * 2) .tostring ();
Return Result;
}
Static void
Main
()
{
String text = "i Have 200 DOLLARS";
String results = regex.replace (text, @ "/ d ",
New matchevaluator (regularExpressions.captext);
System.console.writeline ("Result = [" result "]");
}
}
Look at the results, great, my money has become twice!
However, the purpose of this article is to provide you with a convenient and easy test class, so we overload the above repalCematch method, which also allows custom conversion formulas as incubamer:
Public Static String ReplaceMatch (String Expression, Regexoptions Option, String MS,
Matchevaluator EVALUATOR)
{
Regex regex = new regex (Expression, Option);
String result = regex.replace (ms, evatarator);
Console.writeline ("------------------------------");
Console.writeline ("String: /" {0} / ", expression: /" {1} / ", replace by a evatarator.", MS,
Expression);
Console.writeline ("Replace Result String IS: /" {0} / ", longth: {1}", Result.Tostring (), Result.Length
Return Result;
}
Split string
Regex also provides methods split split from a matching location to split string. This method also has multiple overloads, but these are not focus, everyone can see the document themselves. We continue to complete our methods for testing:
Public Static Void Splitmatch (String Expression, Regexoptions Option, String MS)
{
Regex regex = new regex (Expression, Option);
String [] result = regex.split (ms);
Console.writeline ("------------------------------");
Console.writeline ("String: /" {0} / ", Expression: /" {1} / ", Split Result IS:", MS,
Expression);
FOREACH (String M in Result)
{
Console.writeline ("splited string is: /" {0} / ", length: {1}",
M.Tostring (), M.Length);
}
Console.writeline ("SPLITED Count: {0}", Result.Length);
}
Simple code, not much explanation. Directly come to a smAPLE to see the results:
Splitmatch (@ "/", regexoptions.none, "2004/4/25");
Output:
----------------------------------
String: "2004/4/25", Expression: "/", Split Result IS:
Splited String IS: "2004", Length: 4
Splited String IS: "4", Length: 1
SPLITED STRING IS: "25", Length: 2
SPLITED COUNT: 3
The results are obvious, homing.
My purpose
I wrote so much, look back, I didn't introduce the rules and keyword after the regular expression. Don't worry, this is not a focus. At the beginning of the article, I said that the rules of the regular expression are too complicated. Even MSDN also said that all expression rules cannot be illustrated in a table. My purpose is very simple, introducing several major functions of Regex (match, replacement, and splitting), and provides several simple and convenient test functions. Let you test whether your understanding of the regular expression is accurate.
For example, if you want to confirm the role of ^ $, you can put into this (Input, Expression) data:
("123", "^ / D $") ("123AAA456", "^ / D ") ("123AAA456", "123 &")
Confirmation / d, / s, / w, / w, can test this:
("123ABC GC 456", "/ D ") ("123ABC GC 456", "/ S ")
("123ABC GC 456", "/ W ") ("123ABC GC 456", "/ W ") Compare? * The difference between * can use this data:
("A123 ABCD", "A / D?") ("A123 ABCD", "A / D ") ("A123 ABCD", "A / D *")