This seems to match the rules I have defined, but I only starting learning regex tonight, so I am wondering if it is correct.
Rules:
I suggest writing some unit tests to put the Regex through it's paces. This will also help a few months from now when you find a problem with the Regex and need to update it.
By the looks of it, that rule wouldn't match something like "a_bc", "ab_c", "a_b" or "a_b_c".
Try: /^[a-zA-Z0-9]+([_\s\-]?[a-zA-Z0-9])*$/
which matches the above cases but not any combination of spaces, dashes or underscores next to each other. Eg: "_-" or " _" are not allowed.
You regular expression can be simplified to:
/^[a-zA-Z0-9]+([_ -]?[a-zA-Z0-9])*$/
Visualized with Regexper:
As you can see a user name always has to start with an alphanumeric character. Special characters (_
, ,
-
) have to be followed by an alphanumeric character. The last character has to be an alphanumeric character.
Alphanumerical isn't just [a-zA-Z0-9]
, it's accented, Cyrillic, Greek and other letters, which can be used in username.
(_|-| )
can be replaced by [-_ ]
character class
In my opinion, adding a limited scope to this model would be better
[a-zA-Z0-9]+([_ -]?[a-zA-Z0-9]){5,40}$
Another recommendation for Expresso 3.0 here - very easy to use and build up strings with.