如何反向引用“内部"正则表达式中的选择 ( () )? [英] How to back reference "inner" selections ( () ) in a regular expression?
问题描述
你如何在正则表达式中引用内括号?
示例数据是一个产品价格表,根据购买数量显示不同的价格区间.格式为quantityLow -quantityHigh : pricePer ;倍数.
The sample data is a product price list showing different price breaks based on quantity purchased. The format is quantityLow - quantityHigh : pricePer ; multiples.
我使用 LINQPad 构建了这个 C# Regex 表达式来分离各个部分,它显示了 Regex 数据分离的便捷可视化.在这个例子中,有内部"括号(选择),创建了一个分层的数据结构.
I used LINQPad to construct this C# Regex expression to separate the parts, which shows a handy visualization of the Regex data separation. In this example, there are "inner" parenthesis (selections), creating a hierarchical data structure.
string mys = "1-4:2;5-9:1.89";
Regex.Matches (mys, @"((\d+)[-|\+](\d*):(\d+\.?\d*);?)").Dump(); // Graphically show
这分解为(比赛就是一切.在比赛中,有单场比赛和小组赛.小组赛中有几场单场比赛.)
This breaks down to (Match is everything. Within match, there is a single match and a group match. Within the group match is a few single matches.)
- MatchCollection(2 项)
- 集体收藏(4 项)
- CaptureCollection (1 item) () Group "1-4:2;"
- CaptureCollection (1 项) () 组1"
- CaptureCollection (1 项) () 组4"
- CaptureCollection (1 item) () Group "2"
- CaptureCollection (1 项) () 组5-9:1.89"
- CaptureCollection (1 项) () 组5"
- CaptureCollection (1 item) () Group "9"
- CaptureCollection (1 项) () 组1.89"
仅供参考:
- () 括号组找到了可以通过 \1..\9 引用的结果(我认为).
- \d 匹配单个数字.后面的 + 匹配一位或多位数字.* 匹配零个或多个数字后.?after 说这个匹配是可选的.
- .匹配单个字符.\.在这种情况下匹配句点或小数.
推荐答案
Just use
\1
...\9
(or$1
...$9
在某些正则表达式实现中),就像您通常会做的那样.编号是从左到右,基于开放括号的位置(因此嵌套组的编号大于嵌套组的编号).Just use
\1
...\9
(or$1
...$9
in some regex implementations) like you normally would. The numbering is from left to right, based on the position of the open paren (so a nested group has a higher number than the group(s) it's nested within).这篇关于如何反向引用“内部"正则表达式中的选择 ( () )?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 集体收藏(4 项)