开发者

Regular Expression .Net: what do the sharp brackets mean in a capturing group?

SearchPattern = (?<price1>[0-9]+)(?<price2>[9]?)+(.)(?<price3>[9]{2})

zero or more matches of 0-9 numbers followed by one or more 9 followed by 2 optional digits after the dot.

I did not understand, what does price1, price2, price3 mean?

ReplacementPattern = (?<price1>[0-9]+)(?<price2>[0-9]{1})+(.)(?<price3>[0-9]{2}) 
Replacement S开发者_运维百科tring = ${price1}9


They are named capturing groups. The allow you to refer to the capture group by name when replacing text or retrieving the actual matching text.

For example:

var match = Regex.Match("349.99", "(?<price1>[0-9]+)(?<price2>[9]?)+(.)(?<price3>[9]{2})");
Console.WriteLine("price1 = {0}", match.Groups["price1"].Value);

This will print price1 = 349.


What dot?

(.) will match any character, not just a ..

You probably want (\.).

Edit: Your check for 2 optional digits is also incorrect. You would have to explain in more detail what you are looking for, for anyone to suggest a solution.


price1, price2, and price3 are names given by the author of the regex to the groups in parentheses.

So for example, in (?<price1>[0-9]+), the regex engine will capture one or more digits and put the string into a group named price1.


http://www.regular-expressions.info/refext.html

Round brackets group the regex between them. They capture the text matched by the regex inside them that can be referenced by the name between the sharp brackets. The name may consist of letters and digits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜