Search code examples
c#regexcharacter-class

Why "[" gets matched by [a-zA-Z]


Regex oRegex = new Regex(@"test[a-zA-z]");
string st = @"this is a test1 and testA and test[abc] another testB and test(xyz) again.";
foreach(Match match in oRegex.Matches(st))
{
     Console.WriteLine(match.Value);
}

Output:

testA

test[

testB

Question: Why test[ in the output? The character class [a-zA-Z] is supposed to match only alpha characters a through z and A through Z.


Solution

  • You have a typo in your regex. [a-zA-z] should be [a-zA-Z].

    The character [ is between the A and z characters.