[英]How to repair my C# regex that attempts to match 1-100 characters of letters, numbers, spaces, underscores and dashes
So I have a field 所以我有一个领域
[RegularExpression(@"([A-Za-z0-9\-\_ ]+){1,100}"]
public string Name { get; set; }
where the regex is attempting to match strings that are 1-100 characters long and contains only letters, numbers, underscores, dashes and spaces. 正则表达式试图匹配长度为1-100个字符且仅包含字母,数字,下划线,短划线和空格的字符串。
I am getting the exception 我得到了例外
Additional information: parsing "([A-Za-z0-9-_ ]+){1,100}" - Unrecognized escape sequence _.
附加信息:解析“([A-Za-z0-9-_] +){1,100}” - 无法识别的转义序列_。
How can i fix this? 我怎样才能解决这个问题?
Try this (get rid of the backslash before the underscore): 试试这个(摆脱下划线之前的反斜杠):
[RegularExpression(@"([A-Za-z0-9\-_ ]+){1,100}"]
public string Name { get; set; }
You need to remove all escapes and the +
and it is advisable to put the hyphen at the end of the character class to remove any ambiguity: 您需要删除所有转义和
+
,建议将连字符放在字符类的末尾以消除任何歧义:
[RegularExpression("[A-Za-z0-9_ -]{1,100}"]
Since RegularExpressionAttribute
pattern is always implicitly anchored, there is no need adding ^
in front and $
at the end. 由于
RegularExpressionAttribute
模式始终是隐式锚定的,因此无需在前面添加^
,在结尾添加$
。 [A-Za-z0-9_ -]{1,100}
will match a string that consists of 1 to 100 chars that are either ASCII letters, digits, _
space or -
. [A-Za-z0-9_ -]{1,100}
将匹配由1到100个字符组成的字符串,这些字符可以是ASCII字母,数字, _
空格或-
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.