Regex to match a username

Tofandel picture Tofandel · Feb 8, 2015 · Viewed 7.2k times · Source

I am trying to create a regex to validate usernames which should match the following :

  • Only one special char (._-) allowed and it must not be at the extremas of the string
  • The first character cannot be a number
  • All the other characters allowed are letters and numbers
  • The total length should be between 3 and 20 chars

This is for a HTML5 validation pattern, so sadly it must be one big regex.

So far this is what I've got:

^(?=(?![0-9])[A-Za-z0-9]+[._-]?[A-Za-z0-9]+).{3,20}

But the positive lookahead can be repeated more than one time allowing to be more than one special character which is not what I wanted. And I don't know how to correct that.

Answer

dognose picture dognose · Feb 8, 2015

You should split your regex into two parts (not two Expressions!) to make your life easier:

First, match the format the username needs to have: ^[a-zA-Z][a-zA-Z0-9]*[._-]?[a-zA-Z0-9]+$

Now, we just need to validate the length constraint. In order to not mess around with the already found pattern, you can use a non-consuming match that only validates the number of characters (its literally a hack for creating an and pattern for your regular expression): (?=^.{3,20}$)

The regex will only try to match the valid format if the length constraint is matched. It is non-consuming, so after it is successful, the engine still is at the start of the string.

so, all together:

 (?=^.{3,20}$)^[a-zA-Z][a-zA-Z0-9]*[._-]?[a-zA-Z0-9]+$

Regular expression visualization

Debugger Demo