Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a string like ababba etc

Tags:

regex

pcre

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?

like image 268
Hao Wu Avatar asked Nov 09 '20 08:11

Hao Wu


People also ask

How do you match letters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is the regular expression matching one or more specific characters?

The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus .


3 Answers

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

like image 177
bobble bubble Avatar answered Oct 01 '22 05:10

bobble bubble


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

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

like image 22
Michail Avatar answered Oct 01 '22 05:10

Michail


^(?=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

like image 39
LogicalKip Avatar answered Oct 01 '22 04:10

LogicalKip