Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What regex matches strings of consecutive 'a' and 'b'?

Tags:

regex

I need a regex which matches strings of consecutive a and b, e.g.:

ababa
bab

Edge case (smallest):

ab
ba

(No upper limit.)

...and shouldn't match:

abba
bbab
bbaabb

I've tried several regex but this one is kind of tricky. Can you throw me any hints?

My tries:

  • (a|b)+
  • (ab|ba)*(aba|bab)+

This one gets really close! http://www.regexr.com/38lqg

like image 994
Kenny Meyer Avatar asked Apr 06 '14 13:04

Kenny Meyer


1 Answers

If you want to find matches within a text (potentially several words per line):

\b(((ab)+a?)|((ba)+b?))\b

\b is for word boundary.

like image 133
Karoly Horvath Avatar answered Sep 18 '22 12:09

Karoly Horvath