Reputation: 49
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
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,
\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_-]+)*
.Upvotes: 1