如何使用 C# Regex 转义字符串中的某些字符?
This is a test for % and ' thing? -> This is a test for \% and \' thing?
resultString = Regex.Replace(subjectString,
@"(?<! # Match a position before which there is no
(?<!\\) # odd number of backlashes
\\ # (it's odd if there is one backslash,
(?:\\\\)* # followed by an even number of backslashes)
)
(?=[%']) # and which is followed by a % or a '",
@"\", RegexOptions.IgnorePatternWhitespace);
但是,如果您试图保护自己免受恶意 SQL 查询的侵害,那么正则表达式不是正确的方法。
var escapedString = Regex.Replace(input, @"[%']", @"\$1");
这几乎就是您所需要的。在方括号内,您应该将要转义的每个字符都放在反斜杠中,其中可能包括反斜杠字符本身。
我不认为这可以用正则表达式以良好的方式完成,但你可以简单地运行一个 for 循环:
var specialChars = new char[]{'%',....};
var stream = "";
for (int i=0;i<myStr.Length;i++)
{
if (specialChars.Contains(myStr[i])
{
stream+= '\\';
}
stream += myStr[i];
}
(1) 您可以使用 StringBuilder 来防止创建过多的字符串。