Reputation: 4459
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.
Upvotes: 4
Views: 24352
Reputation: 425448
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.
Upvotes: 8
Reputation: 2047
(?i)([a-z?0-9?\-?]\s?){0,10}
Case insensitive, between 0-10 length, matches any combination of letters, numbers, hyphens and single spaces.
Upvotes: 2
Reputation: 4048
I think no "+" when using range.
^[a-zA-Z0-9]+( [a-zA-Z0-9]{0,10})*$
Also, you say you accept hyphens, but don't see that here?
So
^[a-zA-Z0-9]+( [a-zA-Z0-9\-]{0,10})*$
Upvotes: -1