开发者

Combining Regexes

How can I combine regexes?

EDIT: This if for exam preparation. The question is write a regex to find all strings that have an odd number of a's and an even number of b's?

i.e. instead of | for OR, I need a mechanism to emulate AND

I have two regexes:

1) to find odd number of a's:

^[^a]*a([^a]*a[^a]*a)*[^a]*$

2) to find ev开发者_如何学Goen number of b's:

^([^b]*b[^b]*b)*[^b]*$


You can do this using lookahead expressions (here shown as a verbose regex since it really is hard to read, much more on a single line):

^                                   # start of string
(?=(?:(?:[^a]*a){2})*[^a]*$)        # assert an even number of as
(?=[^b]*b(?:(?:[^b]*b){2})*[^b]*$)  # assert an odd number of bs
.*                                  # match anything
$                                   # end of string

The last two lines can be dropped if you're just validating - they simply match the entire string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜