.NET Regex 重叠匹配数

标签 .net regex

我有这个 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 grouplook-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

enter image description here

关于.NET Regex 重叠匹配数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31509705/

相关文章:

.net - 在同一解决方案/项目中使用 Visual Studio 针对 32 位和 64 位

.net - 为什么 UnhandledExceptionEventArgs.ExceptionObject 是一个对象而不是 Exception?

c# - .NET:向 WebClient 的 UploadStringCompletedEventHandler 提交用户定义标记的最佳方式是什么

regex - 神交 - 如何获得 URIPATHPARAM?

javascript - 正则表达式接受格式为 00.00 的数字

java - String - 所有指定字符串的搜索索引

c# - 序列化包含 List<T> 的 List<T>

c# - 应用程序在 Visual Studio 的单元测试中以 x86 运行,但在独立时以 x64 运行

javascript - 是否有匹配单个字素簇的正则表达式?

字符串的正则表达式包含?