Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#正则表达式-排除下划线&;文本开头和结尾的空格_C#_Regex_Asp.net Mvc - Fatal编程技术网

C#正则表达式-排除下划线&;文本开头和结尾的空格

C#正则表达式-排除下划线&;文本开头和结尾的空格,c#,regex,asp.net-mvc,C#,Regex,Asp.net Mvc,我一直在努力让这个正则表达式工作。 我希望表达式在字符串在开始时或在强结尾结束时包含空间(允许中间的空格)时显示错误。我还想排除下划线和连字符 这就是我目前所拥有的 [RegularExpression(@"^.*\s*[-_]", ErrorMessage = "string cannot begin with or end with a space, or contain a hyphen or underscore")] 这并没有像预期的那样起作用

我一直在努力让这个正则表达式工作。 我希望表达式在字符串在开始时或在强结尾结束时包含空间(允许中间的空格)时显示错误。我还想排除下划线和连字符

这就是我目前所拥有的

[RegularExpression(@"^.*\s*[-_]", ErrorMessage = "string cannot begin with or end with a space, or contain a hyphen or underscore")]
这并没有像预期的那样起作用,有人知道我缺少什么才能让它起作用吗?

你可以使用

[RegularExpression(@“^[^\s_-]+(?:\s+[^\s_-]+)*$”,ErrorMessage=“字符串不能以空格开头或结尾,也不能包含连字符或下划线”)]
详细信息

  • ^
    -字符串的开头
  • [^\s\-]+
    -除空格、
    \
    -
    之外的一个或多个字符
  • (?:\s+[^\s_-]+)*
    -零次或多次重复:
    • \s+
      -一个或多个空格
    • [^\s\-]+
      -除空格、
      \
      -
      之外的一个或多个字符
  • $
    -字符串结束

请参阅。

谢谢wiktor,这正是我所期望的!非常感谢