![](/img/trans.png)
[英]C# regex expression for allowing spaces but not at the beginning, end and repeated spaces
[英]C# Regular expression - exclude underscores & spaces at beginning and end of text
我一直在努力使这个正则表达式起作用。 我希望表达式在字符串的开头或结尾包含空格时显示错误(允许中间有空格)。 另外我想排除下划线和连字符。
这是我到目前为止。
[RegularExpression(@"^.*\s*[-_]", ErrorMessage = "string cannot begin with or end with a space, or contain a hyphen or underscore")]
这不能按预期工作,有人知道我缺少什么才能使其正常工作吗?
您可以使用
[RegularExpression(@"^[^\s_-]+(?:\s+[^\s_-]+)*$", ErrorMessage = "string cannot begin with or end with a space, or contain a hyphen or underscore")]
细节
^
- 字符串的开始[^\\s_-]+
- 除了空格、 _
和-
之外的一个或多个字符(?:\\s+[^\\s_-]+)*
- 零次或多次重复:
\\s+
- 一个或多个空格[^\\s_-]+
- 除了空格、 _
和-
之外的一个或多个字符$
- 字符串的结尾。请参阅正则表达式演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.