Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for username that allows numbers, letters and spaces

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), numbers, spaces, underscores, dashes and dots, but the username must start and end with either a letter or number.

Ideally, it should also not allow for any of the special characters listed above to be repeated more than once in succession, i.e. they can have as many spaces/dots/dashes/underscores as they want, but there must be at least one number or letter between them.

I'm also interested to find out if you think this is a good system for a username? I've had a look for some regex that could do this, but none of them seem to allow spaces, and I would like for the usernames to have some spaces in them.

Thank you :)

like image 808
Daniel Avatar asked Dec 16 '22 22:12

Daniel


1 Answers

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.

  • There will be no consecutive sep without a word in between
  • The first and last char will always be part of a word (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.

References

  • regular-expressions.info/Anchors, Character Class, Repetition, Grouping
like image 99
polygenelubricants Avatar answered Mar 15 '23 11:03

polygenelubricants