Regular Expressions: Restrict Possible Usernames Wrongly Sorted?

My approach was to write the following regular expression:

let userCheck = /^[a-z]{2,}\d*$/i;

It passed all the tests except the following:

Your regex should match Z97

I could see that it could not match ‘Z97’ because of the {2,}, but after a while I decided to check the solution to see what I had missed and it turned out that both solutions had used capturing groups so I was wondering if this challenge could be solved without using capturing groups because if not then shouldn’t this challenge be at least placed after the “Reuse Patterns Using Capture Groups” lesson?

Hello!

Yes, it’s possible separating the matches:

/^[a-c]|[e-g]|[x-z]$/gi

Which would match some letters, for instance: A kind of zombiez, would match ‘a’, ‘f’ and ‘z’.

This serves as an example to how you can combine and use some regex symbols. The characters of start ^ and end $ can be used inside the regex multiple times and | is like an or:

if a character a through c matches at the start: ^[a-c] OR
if a character e through g matches at any place: [e-g] OR
if a character x through z matches at the end of the string: [x-z]$

SPOILERS

Here’s a regex that will work for the challenge:

/^[a-z]{2}$|^[a-z][0-9]{2,}$|^[a-z][a-z]+[0-9]*$/i
1 Like

Thank you so much! I see now how it can be solved with the “or” regex. You basically have to exhaust as many possibilities as if using if-else statements.

1 Like