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?
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_-]+)*
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.