Regex to match a username

2019-03-21 14:45发布

问题:

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.

回答1:

You should split your regex into two parts (not two Expressions!) to make your live 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 arround with the already found pattern, you can use a non-consuming match that only validates the number of characters (its litterally 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 successfull, 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]+$

Debuggex Demo



回答2:

I think you need to use ? instead of +, so the special character is matched only once or not.

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