看看正则表达式背后

时间:2013-07-03 13:23:47

标签: c# regex

我从Regex开始(总是在网上使用我需要的那些)

我需要一些给出输入的东西:

Input: AAABBBCCC
Index: 012345678

正则表达式匹配将是:

  • AA从0,1
  • 来自1,2的AA(即使已经消耗了1的A)
  • BB来自3,4
  • BB从4,5(即使4中的B已被消耗)
  • CC来自6,7
  • 来自7,8的CC(即使已经消耗了7中的B)

我现在的正则表达式是(A{2}|B{2}|C{2})。 这不是我真正的问题,但是对于As,Bs和Cs我有不同的工作方式。

我认为我应该使用一些look behind运算符,但尝试:((A{2}|B{2}|C{2})$1)(?<=(A{2}|B{2}|C{2}))将不起作用。

Here's an example

注意:我的问题在于c#,如果重要

1 个答案:

答案 0 :(得分:5)

你确实需要环顾,但我会使用positive lookahead assertion

(?=(([ABC])\2))

您的匹配结果将位于每个match.Groups(1)对象的match中。

<强>解释

(?=       # Look ahead to check that the following matches:
 (        # Match and capture in group number 1:
  (       # Match and capture in group number 2:
   [ABC]  # Any letter A, B or C
  )       # End of capturing group 2
  \2      # Now match that same letter again.
 )        # End of group 1. It now contains AA, BB or CC
)         # End of lookahead assertion

更简单的解决方案:

(?=(AA|BB|CC))