简体   繁体   中英

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
{
}

This code is throwing NestedQuantifier exception. Can any one know why?

Here is a fixed code:

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");
    }

See IDEONE demo (changed e.NewTextValue to NewTextValue for demo purposes).

There are several points of interest:

  • Regex.IsMatch accepts a string , not a Regex object, as its second parameter
  • .NET regex does not support possessive quantifiers that you were using (at the end of your regex, there was {0,5}+ - and that + caused the nested quantifier issue).
  • Also, there must be no space between a pattern and the limiting quantifier that restricts the pattern length. So, when you define the pattern as [a-zA-Z \\n] {0,5} , the {0,5} is applied to the space that stands next to it on the left, and the meaning of the regex is somewhat distorted.

Please, change

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM