Reputation: 41
I am struggling to write a regex on code camp which must fit the following 4 constraints defined for a correct 'username'
1) Usernames can only use alpha-numeric characters.
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.
3) Username letters can be lowercase and uppercase.
4) Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.
Here is the Regex I came up with, in the following code (first line)
let userCheck = /[a-zA-Z]([a-zA-Z]+\d*|\d\d+)/; // the regex I wrote
let result = userCheck.test(username);
However, it displays the following fault
Your regex should not match BadUs3rnam3
Your regex should not match c57bT3
I am absolutely confused. I actually know what the correct regex to this problem is, however, I need to know where my own regex is going wrong which is producing the above error. Please help
Upvotes: 1
Views: 1257
Reputation: 51
Since this question is on free Code Camp and i have also attempted this one with the help of the hit given by them which suggests this as the solution
let username = "JackOfAllTrades";
let userCheck = /^[a-z][a-z]+\d*$|^[a-z]\d\d+$/i;
let result = userCheck.test(username);
console.log(result)
but in my opinion the above regex pattern does not conform to the fourth condition that is given in the question which is
Usernames have to be at least two characters long. A two-character username can only use alphabet letters as characters.
Upvotes: 0
Reputation: 163632
Your code passes because you are not using anchors so you get a partial match.
You could update the pattern to ^[a-zA-Z](?:[a-zA-Z]+\d*|\d{2,})$
Another way to write it could be matching either 2 chars a-zA-Z and 0+ digits, or in case there is a single char a-zA-Z, match 2 or more digits to pass the rule A two-character username can only use alphabet letters as characters.
^(?:[a-zA-Z]{2,}\d*|[a-zA-Z]\d{2,})$
let userCheck = /^[a-zA-Z](?:[a-zA-Z]+\d*|\d{2,})$/;
[
"BadUs3rnam3",
"c57bT3",
"aa",
"a111111",
"a1",
"11"
].forEach(username => console.log(username + ": " + userCheck.test(username)));
Upvotes: 1