Search code examples
regexpcre

Regex to match a string like ababba etc


Write an expression to match strings like a, aba, ababba, ababbabbba, etc. The number of consecutive b increases one by one after each a.

I'm learning regex and struggling with this regex quiz for several days but still couldn't quite get it right.

According to the description, the regex should match and fail following cases:

Pass cases:

  • a
  • aba
  • ababba
  • ababbabbba
  • ababbabbbabbbba

Fail cases:

  • aa
  • abbaa
  • aabb
  • abababa
  • ababbba

Here's what I tried so far

^a((b(?2)?)a)?(?1)*$

I'm thinking to use recursion but I don't know how to make the recursion add just one b after each a is met. So my solution also passes abba and ababbba etc.

Any ideas? What did I miss?


Solution

  • 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).