1

我正在搜索包含“a”和“b”的字符串的正则表达式,该字符串具有以下两个属性:1:字符串具有偶数个字符2:字符串可能不包含“aa”

4

3 回答 3

1

使用标准(旧)正则表达式是可能的:

(ab|bb|(ba)*bb)*(ba)*

于 2012-04-18T09:51:09.630 回答
1

怎么样:

/(?=^(?:..)+$)(?!aa)(?=.*a)(?=.*b)/

解释:

/         : delimiter
          : control there are an even number of char
  (?=     : positive lookahead
    ^     : begining of string
    (?:   : non capture group
      ..  : 2 characters
    )+    : one or more times
    $     : end of string
  )
          : control there aren't aa
  (?!     : negative look ahead
    aa    : aa
  )
          : control there is at least an a
  (?=     : positive lookahead
    .*a   : at least an a
  )
          : control there is at least a b
  (?=     : positive lookahead
    .*b   : at least a b
  )
/         : delimiter
于 2012-04-18T10:08:22.943 回答
0

使用 Perl 兼容的正则表达式可以轻松完成: ^(ab|bb|(ba(?!a)))*$

基本上它说字符串必须由ab, bb,ba以任何顺序混合的子字符串组成,但ba不能跟随另一个a字符。

字符串的长度是偶数,因为所有这些子表达式的长度都是偶数。aa不能出现在字符串中,因为它出现的唯一方法是在 substring 中baab,但是正则表达式特别限制 ba 后面跟a.

于 2012-04-18T09:30:17.917 回答