Tofandel
Tofandel

Reputation: 3565

Regex to match a username

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

This is for an HTML 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.

Upvotes: 5

Views: 7910

Answers (2)

dognose
dognose

Reputation: 20889

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

Upvotes: 16

user4516901
user4516901

Reputation:

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}

Upvotes: 0

Related Questions