Regex to match a string like ababba etc

Based on @Michails great answer - I played and tried to get it below 12 characters. With 10 (demo)


Still I wonder, if it works fine. It will be definetly faster with start anchor (demo).


  • ^ From the beginning :
  • (?=aba|a$) Will start by aba to make sure it starts with one b (no match, just a check)
  • a(b+) An a followed by several b (capture the number of b)
  • (?=a\1ba) this abbb must be followed by a, one more b, then a
  • |a$ except for the last one of course, which is simply followed by the last a
  • * repeat this pattern of "ab+ with one more b each time"
  • a$ match the final a

Test it on

You would try this: ^((?(1)b\1|a))+$