For complex string replacement that meets certain rules,Regular ExpressionIt is undoubtedly a powerful and efficient choice.
I have also written several posts on the use of regular expressions. For details, see the following address.
Http://zu14.cn/tag/regex/
Today, let's talk about it in. net.Regular ExpressionTIPS:Group replacementHere are two examples to illustrate this problem:
A string that replaces the content in the form of ax and Ay with the form of ax (that is, And ay), Where X and Y are numbers and the bit length is 1 ~ 2, and will not appear in the form of a row connection
After analyzing the above requirements, we can conclude that:The above matching rules are divided into two groups: (ax) and (, ay ).After the match, the first group is returned.
For. net, there are multiple methods to implement group replacement. Here I will show two of them. For the above example, I useMatchevaluatorMethod
Static string customreplace (system. text. regularexpressions. match m) {return M. groups [1]. value; // directly return group 1} string sourcestring = "..... "; string pattern = @" (a \ D {1, 2}) (, A \ D {1, 2}) "; system. text. regularexpressions. matchevaluator myevaluator = new system. text. regularexpressions. matchevaluator (customreplace); system. text. regularexpressions. regEx Reg = new system. text. regularexpressions. regEx (pattern, system. text. regularexpressions. regexoptions. ignorecase | system. text. regularexpressions. regexoptions. multiline); string resultstring = reg. replace (sourcestring, myevaluator );
A piece of HTML code is used to insert Flash in the form of <embed width = "1000" src = "..." ...> </Embed>
The requirement is to customize the flash code.WidthReplace with custom value
In this example, we use the group number$ #,#Represented by numbers. After analysis, we can conclude that the above content is divided into three groups.
String sourcestring = "..."; string towidth = "300"; // custom width string pattern = "(<embed. +? Width \ s {0 ,}=\\ s {0 ,}\ "{0, 1}) (\ D +) (\" {0, 1}) "; system. text. regularexpressions. regEx Reg = new system. text. regularexpressions. regEx (pattern, regexoptions. ignorecase | regexoptions. multiline); string resultstring = reg. replace (sourcestring, "$ {1}" + towidth + "$ {3 }");
To distinguish group numbers from common characters, you can use {} to mark group numbers.