Wondering why my REGEX isn't working?

Tell us what’s happening:
Could somebody explain what I’m doing wrong?
I’ve tried searching for regex testers and it seems to work but somehow it isn’t fulfilling the test cases.

Your code so far

let username = "JackOfAllTrades";
let userCheck = /^\D+\d*$|[a-z][a-z]/gi; // Change this line
let result = userCheck.test(username);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36

Challenge: Restrict Possible Usernames

Link to the challenge:

I recommend testing your regex here https://regexr.com . I recommend against using \D and /g for this challenge.

Hi @azrul.naut ,

Let’s try to dissect your regex by going back to the rules on this challenge:

  1. Usernames can only use alpha-numeric characters.
    — Here you used \D+, hence your test will fail on (J%4)

  2. The only numbers in the username have to be at the end. There can be zero or more of them at the end. Username cannot start with the number.
    — Here you used \d*$, this is fine

  3. Username letters can be lowercase and uppercase.
    — Here you used the i flag; this is fine

  4. Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.
    — Here you used [a-z][a-z], this is fine; however, you need to reposition this on your regex
    — Here your test will fail on (“BadUs3rnam3”) because the other part of your regex [a-z][a-z] found a match, which is “Ba” and so returns ‘true’; your regex failed to meet rule no.2
    — Here your test will fail on (“A1”), as a result of ^\D+\d*$ on your regex; it will return ‘true’, when it should be ‘false’

My suggestion:

Create two non-capturing groups; one group to handle the beginning alphabet character set; and the other group to handle the ending, which should give two options (OR):
— first option:
to meet rule 4, this should take care of the occurrence of one or more alphabetic characters, and a possible occurrence of zero or more digits at the end
— second option:
to handle a case like (“Z97”), the ending should be able to handle two or more occurrences of digits

Hope this explains where the errors come from. Happy coding!

1 Like

Thank you for dissecting it so clearly! Really appreciate it!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.