Reputation: 17
I am trying to write a regex to match strings with even instances of ab and ba with only the alphabet of {a,b}.
I am trying to do so with only |
and *
operators. I think it has something to do with the number of times I switch letters needing to be even.
Ex: aba
is accepted (1 ab and 1 ba). It switches between characters twice.
aaaa
is accepted as it has 0 instances of ab and ba and switches characters 0 times.
I am really struggling to generate the regex.
I tried regexes like (a*b*a*)|(b*a*b*)
and a few others but I cannot seem to solve it.
Upvotes: 0
Views: 208
Reputation: 183514
If a string contains only a's and b's, then the number of occurrences of ab
will be equal to the number of occurrences of ba
if and only if it starts and ends with the same letter.
So you can write: a(a|b)*a|b(a|b)*b
Upvotes: 2