Reputation: 17622
I am using following regex to have validation like
String should be alpha numeric with space, hyphen and underscore in them
[^-\s][a-zA-Z0-9_\s-]+$
But this is NOT accepting single character input. Can anyone please help me to achieve the same validation and also accept a single character alpha numeric?
Upvotes: 1
Views: 784
Reputation: 167962
The regex [^-\s][a-zA-Z0-9_\s-]+$
is looking for:
So it requires at least two characters to find a match.
If you take the second character set [a-zA-Z0-9_\s-]
and exclude space and hyphen from it (as you require at the beginning of the string) then you get [a-zA-Z0-9_]
.
So, you want to match on:
^[a-zA-Z0-9_][a-zA-Z0-9_\s-]*$
Since \w
is an equivalent regular expression character class to [a-zA-Z0-9_]
then this can be simplified to:
^\w[\w\s-]*$
Upvotes: 1
Reputation: 785058
This regex should work:
^[\w-][\w\s-]*$
This will let first character be hyphen OR a alpha-num but rest 0 OR more characters be any combination of alpha-num OR space OR hyphen
Please note \w
represents [A-Za-z0-9_]
If you only want first character to be alpha-num then use:
^\w[\w\s-]*$
Upvotes: 4
Reputation: 22457
So your string should not not start with "not space or hyphen" but rather the inverse: with 'a-z, 0-9, _'.
Try this instead:
^[a-zA-Z0-9_][a-zA-Z0-9_\s-]*$
One character in the first character class is required, and does not contain the space or hyphen. After that, anything goes -- zero or more times.
Upvotes: 1