I\'m looking for some regex code that I can use to check for a valid username.
I would like for the username to have letters (both upper case and lower case), number
So it looks like you want your username to have a "word" part (sequence of letters or numbers), interspersed with some "separator" part.
The regex will look something like this:
^[a-z0-9]+(?:[ _.-][a-z0-9]+)*$
Here's a schematic breakdown:
_____sep-word…____
/ \
^[a-z0-9]+(?:[ _.-][a-z0-9]+)*$ i.e. "word ( sep word )*"
|\_______/ \____/\_______/ |
| "word" "sep" "word" |
| |
from beginning of string... till the end of string
So essentially we want to match things like word
, word-sep-word
, word-sep-word-sep-word
, etc.
sep
without a word
in betweenword
(i.e. not a sep
char)Note that for [ _.-]
, -
is last so that it's not a range definition metacharacter. The (?:…)
is what is called a non-capturing group. We need the brackets for grouping for the repetition (i.e. (…)*
), but since we don't need the capture, we can use (?:…)*
instead.
To allow uppercase/various Unicode letters etc, just expand the character class/use more flags as necessary.