[Convert] C # RegEx into regular expressions

Source: Internet
Author: User
Tags first string

From http://hui06242007.blog.163.com/blog/static/46967621200851931436619/

C # RegEx in-depth Regular Expressions

Regular Expressions is a set of syntax matching rules. Various languages, such as Perl,. net, and Java, have their own shared Regular Expression Libraries. In. net, this class library is called RegEx.
To put it simply, RegEx is an application class used to find matching strings from the character window. With RegEx, programmers can easily extract the data information they need from a piece of data. Here is a simple example to give you a general understanding of RegEx:
RegEx = new RegEx (@ "d + ");
Match m = RegEx. Match ("fox9212 gold ");
Console. writeline (M. value. tostring ());
The result is obvious. RegEx finds the numeric string in the string "Fox 9212gold" and the output result is "9212 ".
After having a basic concept for RegEx, I need to tell you a very good news that RegEx can do more than that for us, it is a set of powerful syntax matching rules. Of course, there is still a bad message waiting for us, that is, the powerful syntax rules naturally require a large number of complicated keyword support, which also brings great difficulties to RegEx learning. To really grasp the regular expression, not a few samples can be fully revealed and explained.

Create a RegEx object
There are three RegEx constructor types. We will not discuss the default constructor here. In the other two constructors, one constructor receives the regular expression string as the input parameter, and the other uses the regular expression string and regexoptions as the input parameter. For example:
 
RegEx = new RegEx ("W + $ ");
RegEx = new RegEx ("s +", regexoptions. ignorecase | regexoptions. multiline );
Regexoptions can provide some special help for us. For example, ignorecase can ignore case sensitivity during matching, and Multiline can adjust the meaning of ^ and $ to match the beginning and end of a row.
We constructed a regular expression above, but we didn't use it to do anything. Now we can use the following methods to perform operations on string objects.
Match string
RegEx has two matching methods: Match () and matches (), which respectively indicate matching one and matching multiple results. Matches is used to show how to use RegEx to obtain and display the matching string.
 
Public static void showmatches (string expression, regexoptions option, string MS)
{
RegEx = new RegEx (expression, option );
Matchcollection matches = RegEx. Matches (MS );
// Show Matches
Console. writeline ("////////////////----------------------------------////////////////");
Console. writeline ("string:" {0} "expression:" {1} "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 ("matched count: {0}", matches. Count );
}
The matched method compares the input parameter strings and regular expressions to find all the matching results and transmits the results as matchcollection. In this way, you can quickly obtain all the results by simply traversing the collection.

Group concept

When you get such a string "the final score is: 19/24", you certainly want to have a regular expression that not only can find a string like data1/data2, data1 and data2 should also be directly transmitted as separate results. Otherwise, you need to analyze the string in the form of "19/24" to obtain the score of both parties. Obviously, regular expressions do not ignore this issue, so it adds the group concept. You can put the search results into different groups respectively, and obtain the results of these groups by group name or group. For example, in the above example, we can use @ "(\ D +)/(\ D +)" as the expression. Let's take a look at the results:
 
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 ("capture group" {0} "value is:" {1} "", name, M. Groups [name]. value );
}
}
Console. writeline ("matched count: {0}", matches. Count );
Output:
////////////////----------------------------------////////////////
Capture group "0" value is: "19/24"
Capture group "1" value is: "19"
Capture group "2" value is: "24"
Matched count: 1

Now it is clear that the RegEx object puts the matching results into group 0. At the same time, the matched group information is also placed in the corresponding group. By default, the group name is an integer that increases from 1. 0 is the reserved name, which is used to indicate the entire string to be matched. Since there is a "default situation" concept, it naturally means that you can customize the group name. The method is very simple. Add the following before the Group :? <Name>. Now, change the regular expression @"(? <Score1> \ D + )/(? <Score1> \ D +) ", now let's look at the result:
////////////////----------------------------------////////////////
Capture group "0" value is: "19/24"
Capture group "score1" value is: "19"
Capture group "score2" value is: "24"
Matched count: 1

Change it to your own name, haha! To make it easier to see all the results in future tests, we have made a small adjustment to the showmatches () We have discussed earlier. In this way, if the expression contains the Group definition, we can also directly view all the group information without modifying any code. The adjusted method showmatchespro () as follows:

Public static void showmatchespro (string expression, regexoptions option, string MS)
{
RegEx = new RegEx (expression, option );
Matchcollection matches = RegEx. Matches (MS );
// Show Matches
Console. writeline ("////////////////----------------------------------////////////////");
Console. writeline ("string:" {0} "expression:" {1} "match result is:", MS, expression );
Foreach (Match m in matches)
{
Foreach (string name in RegEx. getgroupnames ())
{
Console. writeline ("capture group" {0} "value is:" {1} "", name, M. Groups [name]. value );
}
}
Console. writeline ("matched 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} "", name );
}
}
Replace string
RegEx also provides a convenient matching result replacement function. To facilitate the test, we also write the method as follows:

Public static string replacematch (string expression, regexoptions option, string MS, string REP)
{
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 generally accepts two strings as input parameters. The first string is the input string. The second string is used to replace the matching string. It can contain special strings to represent special conversions.

Special string replacement result
$ & Matched string, or $0
$1, $2,... match the corresponding group in the string and use the index
$ {Name} matches the corresponding group in the string with the name
$ 'Match the string before the position
$ 'String after matching position
$ A '$' character
$ _ Input string
$ + Data in the last group that matches the string

Have you read so many strange special strings? Well, let's get two samples to see the results!
Sample1:
Replacematch (@ "\ D +", regexoptions. None, "FEF 12/21 DF 33/14 727/1", "<$ &> ");
Output, All numeric 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 data matched by data1/data2 is 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 about it? The RegEx features are rich enough! However, maybe your requirements are not that simple. For example, you need to double the money in the middle of "I have 200 dollars". What should you do? I fainted, as if there were no ready-made items to use. It doesn't matter. RegEx has better functions. It allows you to define conversion formulas by yourself.
 
Using system. Text. regularexpressions;
Class regularexpressions
{
Static string captext (Match m)
{
// Get the matched 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 result = RegEx. Replace (text, @ "d +", new matchevaluator (regularexpressions. captext ));
System. Console. writeline ("result = [" + Result + "]");
}
}
Look at the results. That's good. My money has actually doubled!
However, the purpose of this article is to provide you with a convenient and easy-to-use test class. Therefore, we reload the repalcematch method above and allow custom conversion formulas as input parameters:

Public static string replacematch (string expression, regexoptions option, string MS,
Matchevaluator evaluator)
{
RegEx = new RegEx (expression, option );
String result = RegEx. Replace (MS, evaluator );
Console. writeline ("////////////////----------------------------------////////////////");
Console. writeline ("string:" {0} ", expression:" {1} ", replace by a evaluator.", MS, expression );
Console. writeline ("replace result string is:" {0} ", Length: {1}", result. tostring (), result. Length );
Return result;
}
Split string

RegEx also provides a method to split strings from matching locations. This method also has multiple reloads, but these are not the focus. You can read the document by yourself. We continue to complete our method for testing:
Public static void splitmatch (string expression, regexoptions option, string MS)
{
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 );
}
The code is simple and not much to explain. Let's look at the result with a smaple:
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 purpose of this article is very simple: introduce several major features of RegEx (matching, replacement, and splitting), and provide several simple and convenient test functions. This allows you to test whether your understanding of regular expressions is accurate.

For example, to confirm the role of ^ $, you can put the (input, expression) data as follows:
("123", "^ \ D + $") ("123aaa456", "^ \ D +") ("123aaa456", "123 &")

Check the function of \ D, \ s, \ W, \ W. You can test it as follows:
("123abc GC 456", "\ D +") ("123abc GC 456", "\ s + ")
("123abc GC 456", "\ W +") ("123abc GC 456", "\ W + ")

Comparison? + * You can use the following data for the difference:
("A123 ABCD", "A \ D ?") ("A123 ABCD", "A \ D +") ("A123 ABCD", "A \ D *")

Related Article

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.