Regex to validate length of alphanumeric string

dtsg picture dtsg · Jul 25, 2013 · Viewed 19.8k times · Source

I have the following regular expression:

^[a-zA-Z0-9]+( [a-zA-Z0-9]+)*$

I'm trying to validate a string between 0-10 characters, the string cannot contain more the two spaces in a row or cannot be empty. The string cannot contain any special characters and can be case insensitive and can include hyphens.

How can I limit input to between 0-10 characters?

I tried

^[a-zA-Z0-9]+( [a-zA-Z0-9]+{0,10})*$

but it does not work.

Answer

Bohemian picture Bohemian · Jul 25, 2013

I would do it like this:

^(?!.*  )(?=.*[\w-])[\w -]{1,10}$

This uses a negative look-ahead (?!.* ) to assert there are not two consecutive spaces, and a positive look-ahead (?=.*[\w-]) to assert it has at least one non-space character (I assume "empty" means "only spaces").

Note that if it can't be "empty", it can't be zero length, so the length range must be 1-10, not 0-10.

Of tiny note is the fact that you don't need to escape the dash in a character class if it's the first or last character.