Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to validate length of alphanumeric string

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.

like image 527
dtsg Avatar asked Jan 13 '23 19:01

dtsg


1 Answers

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.

like image 79
Bohemian Avatar answered Jan 19 '23 01:01

Bohemian