Regex matches username

I am trying to create regex to check for usernames that must match the following:

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

This is for the HTML5 validation pattern, so unfortunately this has to be one big regex.

So far this is what I have:

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

But a positive look can be repeated more than once, allowing you to be more than one special character that I did not want. And I don’t know how to fix it.

+5
source share
2 answers

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

First, map the format your username should be: ^[a-zA-Z][a-zA-Z0-9]*[._-]?[a-zA-Z0-9]+$

Now we just need to check the length limit. In order not to spoil with the already found pattern, you can use an inappropriate match that checks only the number of characters (this, in turn, is a hack to create and a pattern for your regular expression): (?=^.{3,20}$)

The regular expression will try to match a valid format if the length limit matches. It does not consume, so after its successful completion the engine is still at the beginning of the line.

so, all together:

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

Regular expression visualization

Demo version of Debuggex

+14
source

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

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

0
source

Source: https://habr.com/ru/post/1212894/


All Articles