3

我最近开始学习正则表达式,并试图为上面的问题写一个。如果限制只放在一个字母上(例如,不超过 2 个“b”),这并不困难。

那么答案是:a* c*(b|ε)a* c*(b|ε)a* c*

但是对于 2 个“b”和 3 个“c”,“a”之间可能的排序总数为 24(5 选择 3),因此编写一个包含所有这些可能性的正则表达式将非常繁重(因为我们可以选择任意数量的 bs 和 cs,只要数量分别小于 2 和 3)(例如 bcbcc、cbbcc、bcbc、bcc、b、c、...)。

那么是否可以为问题编写一个简洁的正则表达式,或者至少可以通过简化来写出可能性?

4

2 回答 2

1

怎么样:

^(?=(?:[ac]*b){1,2}[ac]*$)(?=(?:[ab]*c){1,3}[ab]*$)

解释:

^               : begining of string
  (?=           : look ahead
    (?:         : non capture group
      [ac]*     : letters a or c 0 or more times
      b         : letter b
    ){1,2}      : the group must be present once or twice
    [ac]*       : letters a or c 0 or more times
    $           : end of string
  )
  (?=           : look ahead
    (?:         : non capture group
      [ab]*     : letters a or b 0 or more times
      c         : letter c
    ){1,3}      : the group must be present once or three times
    [ab]*       : letters a or b 0 or more times
    $           : end of string
  )
于 2015-09-18T14:11:55.677 回答
-1

我认为在这种情况下,您想否定您正在寻找的内容,因为找到两个以上的 b 或 c 很容易。您可以这样做(?!.*b.*b.*|.*c.*c.*c.*)并说,不要再有 2 b 和 3 c

于 2015-09-18T12:34:09.333 回答