Regular expression concatenation

How to combine regular expressions?

EDIT: This is if for exam preparation. The question is to write a regular expression to find all lines that have an odd number a and an even number b?

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

I have two regular expressions:

1) to find odd number of a's:

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

2) to find even number of b's:

^([^b]*b[^b]*b)*[^b]*$
+3
source share
1 answer

You can do this using lookahead expressions (shown here as a verbose regular expression, since it is really hard to read, and much more on one 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 deleted if you just check - they just match the entire line.

+6
source

All Articles