正则表达式:计算不同地方的出现次数

Regex: Counted occurences in different places

正则表达式是否能够匹配可能被不同模式分隔的模式?

例如:A{3}B{2} 将匹配 AAABB。我怎样才能让它匹配 ABABA?

因为这只是一个例子,我不是在寻找一种方法来匹配 AAABB 的所有排列,而是要学习一种通用方法。 :-)

(?=A{3}B{2})[AB]+

(?=A{3}B{2}) - 给定字符串的正面前瞻,以确保我们正好有 3 个 A 和 2 个 B。如果结果为真,则它开始寻找 [AB]+ 。这与 AAABB 严格匹配。

https://regex101.com/r/6xcNb7/3

已按要求更新,这应该与其他排列匹配。

(?=(?:B*A){3}B*$)|(?=(?:A*B){2}A*$)[AB]{5}

这样就可以了:

^(?=(?:B*A){3}B*$)(?=(?:A*B){2}A*$)[AB]{5}$

Demo & explanation

解释:

^               # beginning of string
  (?=             # positive lookahead, make sure we have after exactly 3 A:
    (?:             # non capture group
      B*              # 0 or more B
      A               # 1 A
    ){3}            # end group, must appear 3 times
    B*              # 0 or more B
    $               # end of string
  )               # end of string
  (?=(?:A*B){2}A*$)     # same explanation as above for exactly 2 B
  [AB]{5}       # we must have 5 A or B
$               # end of string