C#正则表达式组多次捕捉 [英] C# Regex group multiple captures
问题描述
下面的代码返回1:
Regex.Match(AAA,(一))组[ 1] .Captures.Count
不过,我希望收到3:我看到了一个三捕获<。 / p>
您需要或者拿到赛计数:
Regex.Matches(AAA,(一))。伯爵
或量词添加到正则表达式:
Regex.Match(AAA,(A)+)。组[1] .Captures.Count
正则表达式(一)
只有一个 A
相匹配。在上面的第一个例子,该正则表达式可以匹配三次。
在第二个例子中的正则表达式匹配数 A
■在一次捕捉每一个进组1
为了让你应该考虑它们之间的差异,一个选择:
Regex.Matches(AABA,(一))。伯爵//这是3
Regex.Match(AABA,(一)+)。组[1] .Captures.Count //这是2
第二只得到两个捕获,因为它的两个第一个序列相匹配的
取值,但是当它找到一个 b
它停止匹配。在 +
量词只匹配完整的序列。
The following code return 1:
Regex.Match("aaa", "(a)").Groups[1].Captures.Count
But I expect to receive 3: I see three captures of a.
You need to either get the match count:
Regex.Matches("aaa", "(a)").Count
Or add a quantifier to the regex:
Regex.Match("aaa", "(a)+").Groups[1].Captures.Count
The regex (a)
matches only a single a
. In the first example above, that regex can be matched three times.
In the second example the regex matches several a
s at once and captures each one into group 1.
To make a choice you should consider the following differences between them:
Regex.Matches("aaba", "(a)").Count // this is 3
Regex.Match("aaba", "(a)+").Groups[1].Captures.Count // this is 2
The second only yields two captures because it matches the first sequence of two a
s but then it stops matching when it finds a b
. The +
quantifier only matches unbroken sequences.
这篇关于C#正则表达式组多次捕捉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!