我有这个 RegEx 可以找到一个 A、一个 B 和两个 C 的任何排列
(?:(?<A>A)|(?<B>B)|(?<C>C)){4}(?<-A>)(?<-B>)(?<-C>){2}
例如,对于这个组合,我们有 3 个匹配项(位置 1、7、15)
ABCCABCABCABCAABCC
我们需要知道有多少重叠匹配项。在这种情况下,当我们在前 4 个位置找到匹配项时,它会开始在位置 5 中寻找另一个匹配项。
我们需要它开始寻找位置 2 的下一个匹配项,因此匹配项将位于位置:1、2、3、4、7、10、15
在这个例子中我们有 7 个匹配项
1. ABCC
2. BCCA
3. CCAB
4. CABC
7. CABC
10. CABC
15. ABCC
如何使用 RegEx 在下一个位置开始寻找下一个匹配项,而不是在完成序列后的下一个位置?
提前致谢。
最佳答案
您需要使用 capturing group在look-ahead里面:
参见 here :
Lookahead assertions do not consume any characters in the string. As a result, you can use them to find overlapping character sequences.
(?=(?<value>(?:(?<A>A)|(?<B>B)|(?<C>C)){4}(?<-A>)(?<-B>)(?<-C>){2}))
^ ^
If you want to store the match of the regex inside a lookahead, you have to put capturing parentheses around the regex inside the lookahead, like this:
(?=(regex))
.
更多details on overlapping matches using regex可以在 Rexegg.com 上找到。
参见 demo
关于.NET Regex 重叠匹配数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31509705/