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)

(b\1|^a)+$

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


^(?=aba|a$)(?:a(b+)(?=a\1ba|a$))*a$

  • ^ 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 https://regex101.com/r/J5rXH9/3


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

https://regex101.com/r/TGBHzj/1

Tags:

Regex

Pcre