Regular expression to validate username?

I'm still new to using regular expressions, so here is my point. I have some rules for valid usernames, and I'm trying to make an expression for them.

Here they are:

  • 1-15 Characters
  • az, AZ, 0-9 and valid spaces
  • You must start with az or AZ
  • Unable to complete space
  • Cannot contain two spaces in a line

This is, as I understand it.

/^[a-zA-Z]{1}([a-zA-Z0-9]|\s(?!\s)){0,14}[^\s]$/ 

It works, for the most part, but does not match any character like "a".

Can anyone help me here? I use PCRE in PHP, if that matters.

+6
php regex
source share
3 answers

Try the following:

 /^(?=.{1,15}$)[a-zA-Z][a-zA-Z0-9]*(?: [a-zA-Z0-9]+)*$/ 

A simplified statement (?=.{1,15}$) checks the length, and the rest checks the structure:

  • [a-zA-Z] ensures that the first character is an alphabetic character;
  • [a-zA-Z0-9]* allows any number of the following alphanumeric characters;
  • (?: [a-zA-Z0-9]+)* allows any number of sequences of one space (not \s , which allows any space character), followed by at least one alphanumeric character (see PCRE subfolders for syntax (?:…) ).

You can also remove the forward-looking statement and check the length using strlen .

+7
source share

The main problem of your regular expression is that it needs at least two characters, two have a match:

  • one for part [a-zA-Z]{1}
  • one for part [^\s]

Besides this problem, I see some parts of your regular expression that can be improved:

  • The class [^\s] will match any character, with the exception of spaces: a semicolon or a semicolon will be accepted, try using the class [a-zA-Z0-9] here to make sure that the character is correct.
  • You can remove part {1} at the beginning, as the regular expression will match exactly one character by default
0
source share

do everything after your first character extra

 ^[a-zA-Z]?([a-zA-Z0-9]|\s(?!\s)){0,14}[^\s]$ 
0
source share

All Articles