场景:我想把一个字符串里的所有单引号在前面加个反斜杠转义。
首先我们要知道java的单引号是不需要转义的也就是说
System.out.println("'".equals("\'"));
会打印true。Java规定转义斜杠后面跟不是特殊含义的符号,转义斜杠忽略,所以加上也没问题
于是,就只要把单引号替换成前面加个反斜杠:
String s = "SELECT * FROM tbl_user WHERE USER_NAME LIKE '黄%'";
System.out.println(s.replaceAll("'", "\\'"));
System.out.println("'".equals("\'"));
System.out.println("\\n");
然而得到结果:
SELECT * FROM tbl_user WHERE USER_NAME LIKE '黄%'
true
\n
前面加的反斜杠没有出现,纠结了一些时间,突然看到replaceAll方法上面的一个说明:
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; seeMatcher.replaceAll
. Use java.util.regex.Matcher.quoteReplacement
to suppress the special meaning of these characters, if desired.
String s = "SELECT * FROM tbl_user WHERE USER_NAME LIKE '黄%'";
System.out.println(s.replaceAll("'", Matcher.quoteReplacement("\\'")));
System.out.println("'".equals("\'"));
System.out.println("\\n");
得到结果:
SELECT * FROM tbl_user WHERE USER_NAME LIKE \'黄%\'
true
\n
和预期的终于一样了。