Regex to match a username

我的未来我决定 提交于 2019-12-04 13:06:27

问题


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}



来源:https://stackoverflow.com/questions/28392975/regex-to-match-a-username

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!