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.