Regex:username restriction

Regex:username restriction
0

#1

this is my regexp: /^[a-zA-z][a-zA-Z]\d*/ and it passed,but i think it should not !
Bcz it returns true for string abcd1d i.e notice a digit 1 in between.
what should i do to make sure that digit appear at last only??
classroom link
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames


#3

Let me try that again without blurting out a solution.

I believe that you are correct. It appears that the assertion tests do not adequately check the provided regular expressions.

You could use the $ just after the digits to test for end of string but you would need to handle the case where there are more than two letters. I think yours is only testing for two consecutive letters at the beginning of a string.

There are online tools like regexr that let you test drive your regular expressions showing exactly how you match is behaving. I find these useful for both working out problems and general learning.


#4

Another candidate for a Github issue. I will post an issue later today.


#5

OK. I looked at this again and it appears that someone is addressing the issue of numbers not at the end of the string by adding this assertion case BadUs3rnam3

Getting back to your regular expression though.

/^[a-zA-z][a-zA-Z]\d*/ will match password like myTwoCents123 but maybe not in the way you think.

Your expression is looking for two letters at the beginning of a string followed by zero or more digits.
That would match the my of myTwoCents123 - two letters, at the beginning, followed by zero digits - so true is returned. And so it will also match the my in myTwoCents123abc , also returning true. This is probably not what you expected.

SPOILER: I'll try answering only with material already covered in previous challenges.

/^[a-zA-z][a-zA-Z]+\d*/
The additional + changes the regex to look for

  • ^[a-zA-z] - a letter at the beginning of the string
  • [a-zA-Z]+ - followed by one or more letters
  • \d* - followed by zero or more digits

That will match all of myTwoCents123 and most of myTwoCents123abc , both returning true. Still not exactly as expected. Bad passwords still pass the test.

/^[a-zA-z][a-zA-Z]+\d*$/
The $ means end of string so now the regex is looking for

  • ^[a-zA-z] - a letter at the beginning of the string
  • [a-zA-Z]+ - followed by one or more letters
  • \d* - followed by zero or more digits
  • $ - followed by the end of the string

Now that will match myTwoCents123 but not myTwoCents123abc as expected.