[英]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: 我对UI字段进行了正则表达式表达式验证:
^[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. 字符类中的符号,并且还包含
\\s
而不是空格。
@"^[a-zA-Z0-9_-]+(?:\s[a-zA-Z0-9_-]+)*$"
But \\s
matches newline characters also. 但是
\\s
匹配换行符。 So change \\s
to a whitespace in the above regex based upon your needs. 因此,根据需要将
\\s
更改为上述正则表达式中的空格。 The main thing here is the non-capturing group (?:\\s[a-zA-Z0-9_-]+)*
which matches, 这里最主要的是匹配的非捕获组
(?:\\s[a-zA-Z0-9_-]+)*
,
\\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_-]+)*
. \\s
以及以下一个或多个单词或连字符[a-zA-Z0-9_-]+
,零次或多次(?:\\s[a-zA-Z0-9_-]+)*
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.