C#正则表达式逃脱某些角色

时间:2012-06-18 21:11:46

标签: c# regex escaping

如何使用C#Regex转义字符串中的某些字符?

This is a test for % and ' thing? -> This is a test for \% and \' thing?

3 个答案:

答案 0 :(得分:2)

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查询的影响,那么正则表达式不是正确的方法。

答案 1 :(得分:0)

var escapedString = Regex.Replace(input, @"[%']", @"\$1");

这几乎是你所需要的。在方括号内,你应该用反斜杠放置你想要逃避的每个字符,反斜杠可能包括反斜杠字符本身。

答案 2 :(得分:0)

我认为这不能用正则表达式完成,但你可以简单地运行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来防止创建太多字符串。