为什么“[”被[a-zA-Z]匹配

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

输出:

测试A

测试[

测试B

问题:为什么在输出中出现test[?字符 class [a-zA-Z] 应该只匹配字母字符 a 到 z 和 A 到 Z。

因为[属于ascii rangeA-z,所以将字符class中存在的A-z更改为A-Z

Regex oRegex = new Regex(@"test[a-zA-Z]");

您的正则表达式中有错字。 [a-zA-z] 应该是 [a-zA-Z].

字符[Az字符之间。

Z 是你的错字。更改此 [a-zA-Z]

Regex oRegex = new Regex(@"test[a-zA-Z]");