C # A technique of Regular Expressions
A few days ago, because a project needs to use regular expressionsCodeIn the use process, some problems are encountered, but the final solution is solved. Now, write down for yourself or you
For more information, see.
I am grateful for the nstorm and senkiner that helped me solve the problem in csdn ).
The problem is that 25 of the following strings is taken, that is, the value between TD.
<TD width = "17" Height = "12" bgcolor = "# ff0000"> 25 </TD>
Use a regular expression in two ways:
First, there is a related introduction on the Microsoft website, but I just mentioned it and didn't introduce it in detail.
Related urls: http://www.microsoft.com/china/msdn/library/webservices/asp.net/regexnet.mspx
In this example, "Naming group" and "four-way processing" are used in the bottom high-level topic.
The specific method is as follows:
String strtemp = "<TD width = \" 17 \ "Height = \" 12 \ "bgcolor = \" # ff0000 \ "> 25 </TD> ";
RegEx regint = new RegEx ("(? <=>) \ D + (? = <) ", Regexoptions. ignorecase );
Matchcollection matchsint = regint. Matches (strtemp );
MessageBox. Show (matchsint [0]. value );
Second, the usage of the "Naming group" mentioned above. in fact, JS regular expressions also have the same function. I am not very familiar with it. and this is in C,
Therefore, I still paid a weekly discount for using this method.
RegEx reg;
String pattern;
Match m;
String tdvalue;
String STR = @ "<TD width = 34> 564 </TD> ";
Pattern = @ "^ <TD [^>] +> (? <Tdvalue> \ TD +) <[^>] +> $ ";
Reg = new RegEx (pattern, regexoptions. ignorecase );
If (Reg. ismatch (STR ))
{
M = reg. Matches (STR) [0];
Tdvalue = M. Groups ["tdvalue"]. value;
MessageBox. Show (tdvalue );
}
Although the two methods are the results of regular expressions, their ideas are completely different.
The first type of parentheses is a condition, that is, the content of the parentheses is a required condition, and the actual result to be obtained is out of the brackets.
The second type of parentheses is the value. That is to say, the content of the parentheses is the obtained value, while the other is the condition. It is actually grouping .? <XXX> this expression represents? The parentheses in the preceding section are bounded into a group. The group name <> contains the group name. In the result, the result can be obtained with the group name value.
Let's take a look. In this example, Microsoft's advanced regular expressions are all used, and they are all very convenient to get the desired results. These two methods are really hard to learn.