user11163978
user11163978

Reputation:

regex to allow only alphabets and no special characters, with no space at the beginning

I have tried this: but this isn't working as expected. However it restricts user to enter space at the beginning. where did I made the mistake?

Regex that I have tried to build so far: [^-\s][a-zA-Z\s]*$

Should Match: priya, Abc Xyz
Should not match: <spaces>binayak, $&&ay%%aac

Upvotes: 2

Views: 1685

Answers (1)

Sweeper
Sweeper

Reputation: 274480

First of all, you missed the beginning of string anchor ^.

Secondly, the inverse character class [^-\s] is a good attempt at not allowing spaces, but at the same time it does allow other special characters to be at the beginning of the string, which we do not want. Instead, we could just something very similar to the second character class, just without the \s: [a-zA-Z].

Full regex:

^[a-zA-Z][a-zA-Z\s]*$

Upvotes: 1

Related Questions