Regex to match a username

后端 未结 2 1685
生来不讨喜
生来不讨喜 2021-02-10 08:27

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

  • Only one special char (._-) allowed and it must no
相关标签:
2条回答
  • 2021-02-10 08:55

    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

    0 讨论(0)
  • 2021-02-10 09:09

    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}

    0 讨论(0)
提交回复
热议问题