Is it possible to construct such a regex without brace quantifiers?

I’ve already completed the certification projects but decided to complete those unnecessary tasks as well. And I got confused by the exercise “Restrict Possible Usernames”. Note the last condition

  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.

I can write a regex that satisfies the criteria, but only using curly bracket quantifiers

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

The problem is we are not supposed to know them by that point. Basically, so far freeCodeCamp only taught students the following things: [], -, ^, $, ?, *, +, g, i, \d, \D, \w, \W. FCC seems to suggest I can solve this puzzle using those tools only. How?

Tell me in plain English what this pattern is doing.

Matches two or more latin letters

Good. So let’s forget about the “or more” part for the moment and concentrate on matching two latin letters. Without braces, how would you do that? Just give me the pattern for matching exactly two latin letters in a row.

If you’re implying I should’ve written

let userCheck = /^[a-z][a-z]\d*$|^[a-z]\d\d$/i;

then it would possibly violate the DRY principle, not best practice. I thought maybe I could do some tricks with lazy matching. That was new for me

I think you’ll find you need a + after the second [a-z] if you want it to work properly.

You asked how you could solve this without using curly braces. Using [a-z][a-z]+ instead of [a-z]{2,} is the way to do that, especially if the lessons haven’t introduced the curly braces yet (which you implied you weren’t supposed to even know about at this point). There might be other ways to solve this but I have a feeling they would add much more complexity then is necessary. Sometimes simple is good.

This isn’t really a violation of the DRY principle. This is just a matter of convenience. There isn’t that much difference between writing [a-z][a-z]+ and [a-z]{2,}. Now if you wanted to match 3 or more latin letters in a row then I would agree, using the curly braces is the way to go because it would get annoying typing out all of those [a-z] and would open up the possibility of mistakes.

2 Likes

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