gpt4 book ai didi

regex - 为什么 RegularExpressionValidator 不匹配我的正则表达式?

转载 作者:行者123 更新时间:2023-12-01 13:42:38 27 4
gpt4 key购买 nike

我在尝试使用 asp:RegularExpressionValidator 验证 asp:TextBox 控件时遇到问题。我简化了我正在使用的正则表达式,并隔离了 RegularExpressionValidator 在这部分失败:(?=(.*[A-Z]){2}),我不知道为什么。

这部分正则表达式要求输入至少包含两个大写字母。我已经使用 LINQPad 测试了带有“Regex”类的表达式:

Regex.Match("THis", "(?=(.*[A-Z]){2})").Dump();

还有两个在线正则表达式测试器,它可以与他们一起工作。

根据 MSDN documentation 中的备注部分, RegularExpressionValidator 类在客户端使用 JScript 正则表达式语法。我找不到对 JScript 正则表达式语法的任何引用,所以我假设它们指的是 JavaScript,并使用此 Online regex tester 测试了针对 JavaScript 的正则表达式。 ,这表明它适用于 JavaScript。

最佳答案

重点是 RegularExpressionAttribute 需要完整的字符串匹配。它没有记录,但是 C# source code很有说服力:

override bool IsValid(object value) {
this.SetupRegex();

// Convert the value to a string
string stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);

// Automatically pass if value is null or empty. RequiredAttribute should be used to assert a value is not empty.
if (String.IsNullOrEmpty(stringValue)) {
return true;
}

Match m = this.Regex.Match(stringValue);

// We are looking for an exact match, not just a search hit. This matches what
// the RegularExpressionValidator control does
return (m.Success && m.Index == 0 && m.Length == stringValue.Length);
}

See //我们正在寻找完全匹配,而不仅仅是搜索命中。这符合 RegularExpressionValidator 控件的作用

因此,您必须将模式的 consuming .* 部分添加到正则表达式中,因为您的 (?=(.*[A-Z]){ 2}) 只匹配部分,如果字符串中有2个大写ASCII字母,则匹配字符串开头的空格,并且m.Length == stringValue.Length 条件不满足。

其实还可以写成

^(?:[^A-Z]*[A-Z]){2}.*$

参见 regex demo (似乎 ^(字符串开头)和 $(字符串结尾) anchor 在您的代码中是多余的,模式在代码中锚定)。

详细信息:

  • ^ - 字符串的开始
  • (?:[^A-Z]*[A-Z]){2} - 2 个序列:
    • [^A-Z]* - 除 ASCII 大写字母以外的零个或多个字符
    • [A-Z] - 大写 ASCII 字母
  • .* - 除换行符外的任何零个或多个字符
  • $ - 字符串结尾

关于regex - 为什么 RegularExpressionValidator 不匹配我的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38663628/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com