【问题标题】:Regex Nested Quantifier exception while matching regular expression.匹配正则表达式时出现正则表达式嵌套量词异常。
【发布时间】:2016-01-25 06:56:00
【问题描述】:
int characterLimit = 5;
Regex regxForAlpha = new Regex("^[a-zA-Z \n] {0,"+characterLimit.ToString()+"}+$");
if(!string.IsNullOrEmpty(e.NewTextValue))
if (!Regex.IsMatch( e.NewTextValue, regxForAlpha)){
}
else
{
}

此代码抛出 NestedQuantifier 异常。任何人都可以知道为什么吗?

【问题讨论】:

标签: c# regex


【解决方案1】:

这是一个固定的代码:

string NewTextValue = "str";
int characterLimit = 5;
string regxForAlpha = "^[a-zA-Z \n]{0,"+characterLimit.ToString()+"}$";
if(!string.IsNullOrEmpty(NewTextValue))
    if (!Regex.IsMatch( NewTextValue, regxForAlpha)){
        Console.WriteLine("No match");
    }
    else
    {
        Console.WriteLine("Match");
    }

请参阅 IDEONE demo(将 e.NewTextValue 更改为 NewTextValue 以进行演示)。

有几个兴趣点:

  • Regex.IsMatch 接受 字符串,而不是 Regex 对象,作为其第二个参数
  • .NET 正则表达式不支持您正在使用的 占有 量词(在您的正则表达式末尾,有 {0,5}+ - 并且 + 导致了嵌套量词问题)。李>
  • 此外,模式和限制模式长度的限定量词之间不能有空格。因此,当您将模式定义为[a-zA-Z \n] {0,5} 时,{0,5}应用于左侧旁边的空间,并且正则表达式的含义有些失真。

【讨论】:

    【解决方案2】:

    请改一下

    Regex regxForAlpha = new Regex("^[a-zA-Z \n] {0,"+characterLimit.ToString()+"}+$");
    

    Regex regxForAlpha = new Regex("^[a-zA-Z \n] {0,"+characterLimit.ToString()+"}$");
    

    【讨论】:

    • 会引发同样的异常吗?
    • 谢谢@Helen Downs,我找到了解决方案。
    猜你喜欢
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    相关资源
    最近更新 更多