-2

I am looking for a regex that matches the following: 2 times the character 'a' and 3 times the character 'b'. Additionally, the characters do not have to be subsequent, meaning that not only 'aabbb' and 'bbaaa' should be allowed, but also 'ababb', 'abbab' and so forth.

By the sound of it this should be an easy task, but atm I just can't wrap my head around it. Redirection to a good read is appreciated.

Lukas
  • 244
  • 2
  • 13

1 Answers1

-1

You need to use positive lookaheads. This is the same as the password validation problem described here.

Edit:

A positive lookahed will allow you to check a pattern against the string without changing where the next part of the regex matches. This means that you can test multiple regex patterns at the current position of the string and for the regex to match all the positive lookaheads will have to match.

In your case you are looking for 2 a' and 3 b's so the regex to match exactly 2 a's anywhere in the string is /^[^a]*a[^a]*a[^a]*$/ and for 3 b's is /^[^b]*b[^b]*b[^b]*b[^b]*$/ we now need to combine these so that we can match both together as follows /^(?=[^a]*a[^a]*a[^a]*$)(?=[^b]*b[^b]*b[^b]*b[^b]*$).*$/. This will start at the beginning of the string with the ^ anchor, then look for exactly 2 a's then the end of the string. Then because that was a positive lookahead the (?= ... ) the position for the next part of the pattern to match at in the string wont move so we are still at the start of the string and now match exactly 3 b's. As this is a positive lookahead we are still at the beginning of the string but now know that we have 2 a's and 3'b in the string so we match the whole of the string with .*$.

JGNI
  • 3,933
  • 11
  • 21
  • https://stackoverflow.com/questions/9477906/regular-expression-to-check-if-password-is-8-characters-including-1-uppercase-l?rq=1 does not help OP, there is no information about limiting quantifiers applied to groups. *You need to use positive lookaheads* - How? It would make sense to explain the idea in the *answer*. – Wiktor Stribiżew Oct 24 '18 at 10:26