Steelbird
Steelbird

Reputation: 49

C# regex expression for allowing spaces but not at the beginning, end and repeated spaces

I have a regex expression validation for an UI field:

^[a-z|A-Z|0-9|_|\-]+$

Now I need to allow spaces for the entry, so if I add space to the regex expression, like this:

^[a-z|A-Z|0-9|_| |\-]+$

It does allow spaces at the beginning, end and repeated spaces.

Could someone help me with this please?

Upvotes: 0

Views: 69

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

I suggest you to remove the | symbol from the character class and also include \s instead of a whitespace.

@"^[a-zA-Z0-9_-]+(?:\s[a-zA-Z0-9_-]+)*$"

But \s matches newline characters also. So change \s to a whitespace in the above regex based upon your needs. The main thing here is the non-capturing group (?:\s[a-zA-Z0-9_-]+)* which matches,

  • a space \s and also the following one or more word or hyphen characters [a-zA-Z0-9_-]+, zero or more times (?:\s[a-zA-Z0-9_-]+)*.

DEMO

Upvotes: 1

Related Questions