我正在尝试编写一个正则表达式,它接受一个字符串并将它们作为一个范围构建到一个表达式中。我使用 Regex.Escape (.net 3.5) 来清理这些字符串,以便不应该留下任何控制字符。但似乎 Escape 方法没有按预期工作并且不会逃脱关闭 }或 ]人物。不应该逃避这些吗?这是我正在做的一个例子:
string test = @"sdfz346gv][)(}{><";
string pattern = "[" + Regex.Escape(test) + "]+";
string input = "ffff{444}g";
if (Regex.IsMatch(input, pattern))
{
Console.WriteLine("Matched");
}
else
{
Console.WriteLine("Not Matched");
}
pattern字符串似乎具有值 [sdfz346gv]\[\)\(}\{><]+并且不匹配 ffff{444}g但就我而言,它应该看起来像这样 [sdfz346gv\]\[\)\(\}\{><]+这是一个执行不同的表达式并将匹配 ffff{444}g .我可以替换 }和 ]带有 \} 的字符和 \]但是还有没有其他字符不会被这种转义方法转义?我可以依靠它吗?
请您参考如下方法:
来自 here :
Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space) by replacing them with their escape codes.
和
While the Escape method escapes the straight opening bracket ([) and opening brace ({) characters, it does not escape their corresponding closing characters (] and }). In most cases, escaping these is not necessary. If a closing bracket or brace is not preceded by its corresponding opening character, the regular expression engine interprets it literally.
