gpt4 book ai didi

regex - 如何为包含 "a"s、 "b"s 和 "c"s 但不超过 2 "b"s 和 3 "c"s 的所有字符串编写简洁的正则表达式

转载 作者:行者123 更新时间:2023-12-02 04:46:09 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

怎么样:

^(?=(?:[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
)

关于regex - 如何为包含 "a"s、 "b"s 和 "c"s 但不超过 2 "b"s 和 3 "c"s 的所有字符串编写简洁的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32652059/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com