[英]Regular Expression problem (in asp.net MVC5)
hoping someone can point out what I'm missing here with a regular expression. 希望有人可以用正则表达式指出我在这里缺少的内容。
Here is the data item from my model :- 这是我模型中的数据项:
[Display(Name = "Serial to Search")]
[MaxLength(12)]
[RegularExpression(@"ABC|WXYZ\w{8,9}")]
public string SerialNo { get; set; }
This should allow me to match a serial that begins with either ABC or WXYZ and has another 8 or 9 characters/numbers. 这应该允许我匹配一个以ABC或WXYZ开头且又有8或9个字符/数字的序列。
In my view I'm using jquery unobtrusive validation and an @Html.ValidationMessageFor control to display errors. 在我看来,我正在使用jQuery非侵入式验证和@ Html.ValidationMessageFor控件来显示错误。
I have tested this on regex101.com using the following test string :- 我已经使用以下测试字符串在regex101.com上进行了测试:
ABCGC1000BC5
and it passes fine, but in my view I get a validation error, specifically that the string doesn't match the regex requirements. 并顺利通过,但是在我看来,我收到验证错误,特别是该字符串不符合正则表达式要求。 Can anyone see what I'm missing ?
谁能看到我所缺少的吗? Thanks.
谢谢。
Your regex matches two type of strings: 1) ABC
or 2) WXYZ
followed with 8 or 9 word chars. 您的正则表达式匹配两种类型的字符串:1)
ABC
或2) WXYZ
后跟8或9个单词字符。 Remember that RegularExpressionAttribute
pattern must match the whole string. 请记住,
RegularExpressionAttribute
模式必须与整个字符串匹配。 Even if regex101.com shows a match for ABC12
, it won't match in your environment. 即使regex101.com显示与
ABC12
匹配,在您的环境中也不会匹配。
You need to use a grouping, 您需要使用分组,
(ABC|WXYZ)\w{8,9}
^ ^
A non-capturing group would fit even better since you are only validating a string and not using captures later: 一个非捕获组会更好,因为您只验证一个字符串而以后不使用捕获:
(?:ABC|WXYZ)\w{8,9}
^^^ ^
RegularExpressionAttribute
searches for an exact match: if the Regex isn't anchored to beginning or end of the string, then RegularExpressionAttribute
will effectively do that anchoring for you. RegularExpressionAttribute
搜索精确匹配:如果Regex没有锚定在字符串的开头或结尾,那么RegularExpressionAttribute
将为您有效地进行锚定。 See the implementation on ReferenceSource . 请参见ReferenceSource上的实现 。
That is the difference between regex101.com and your test where it fails. 那就是regex101.com和测试失败之间的区别。 If you anchor the regex on regex101.com, as
^ABC|WXYZ\\w{8,9}$
, you will see that it fails. 如果将正则表达式锚定在regex101.com上,如
^ABC|WXYZ\\w{8,9}$
,您将看到它失败。
The reason, as Wiktor Stribiżew pointed out in the comments, is that your regex looks for ABC
OR WXYZ\\w{8,9}
. 正如WiktorStribiżew在评论中指出的,原因是您的正则表达式会寻找
ABC
或WXYZ\\w{8,9}
。 Neither ^ABC$
nor ^WXYZ\\w{8,9}$
match your test string of ABCGC1000BC5
. ^ABC$
和^WXYZ\\w{8,9}$
都不匹配您的ABCGC1000BC5
测试字符串。
Edit: (Please accept Wiktor Stribiżew's answer as the solution. This answer just aims to explain the difference between running it on regex101.com and in ASP.NET). 编辑:(请接受WiktorStribiżew的答案作为解决方案。此答案仅用于解释在regex101.com和ASP.NET中运行它的区别)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.