sanbhat
sanbhat

Reputation: 17622

Regex not accepting single character

I am using following regex to have validation like

Regular expression visualization

Debuggex Demo

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

Answers (3)

MT0
MT0

Reputation: 167962

The regex [^-\s][a-zA-Z0-9_\s-]+$ is looking for:

  • One character that is not a hyphen or space; then
  • One more more alpha-numberic, underscore, space or hyphen characters.

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-]*$
  • One character that can be alpha-numeric or an underscore (at the start of the string); then
  • Zero or more subsequent alpha-numberic, underscore, space or hyphen characters.

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

anubhava
anubhava

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

Jongware
Jongware

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

Related Questions