簡體   English   中英

匹配正則表達式時,Regex嵌套量詞異常。

[英]Regex Nested Quantifier exception while matching regular expression.

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異常。 誰能知道為什么?

這是固定代碼:

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演示 (改變e.NewTextValueNewTextValue用於演示目的)。

有幾個興趣點:

  • Regex.IsMatch接受字符串 (不是Regex對象)作為其第二個參數
  • .NET正則表達式不支持您使用的所有格修飾符(在正則表達式的末尾,出現{0,5}+ -且+導致嵌套量詞問題)。
  • 此外,圖案和限制圖案長度的限制量詞之間不得有空格。 因此,當您將模式定義為[a-zA-Z \\n] {0,5}{0,5}應用於左側旁邊的空格 ,正則表達式的含義是有點扭曲。

請更換

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM