String.replaceAll() 和 StringUtils.replace() 之间的行为差异
Difference in behaviour between String.replaceAll() and StringUtils.replace()
我想用转义单引号替换所有单引号。首先,我尝试使用 String.replaceAll("\'", "\'")
但没有成功。所以,我试过 StringUtils.replace(String, "\'", "\'")
有效。
代码如下:
String innerValue = "abc'def'xyz";
System.out.println("stringutils output:"+StringUtils.replace(innerValue, "\'", "\'"));
System.out.println("replaceAll output:"+innerValue.replaceAll("\'", "\'"));
预期输出:
stringutils output:abc\'def\'xyz
replaceAll output:abc\'def\'xyz
实际输出:
stringutils output:abc\'def\'xyz
replaceAll output:abc'def'xyz
我只是好奇 为什么 String.replaceAll
没有用 \'
替换 '
?
不需要在String
s中对单引号进行转义(仅在char
值中),需要用替换值进行双双转义:
innerValue.replaceAll("'", "\\'")
这是由于replaceAll
将正则表达式作为参数(第二个参数必须支持反向引用的正则表达式)。
您还可以使用 replace
习语,因为您没有使用正则表达式:
innerValue.replace("'", "\'")
备注
replace
方法实际上在幕后使用 replaceAll
,但通过使用 Pattern.LITERAL
标志调用 Pattern.compile
和 Matcher.quoteReplacement
将值转换为文字在更换上。
Java 字符串包 replaceAll 方法需要 RegularExpression 作为字符串参数。
而 Commons Lang StringUtils.replace 需要字符串值。
当涉及到本机 Java 实现时,我们必须进行双重转义。
System.out.println("replaceAll output:"+innerValue.replaceAll("'", "\\'"));
我想用转义单引号替换所有单引号。首先,我尝试使用 String.replaceAll("\'", "\'")
但没有成功。所以,我试过 StringUtils.replace(String, "\'", "\'")
有效。
代码如下:
String innerValue = "abc'def'xyz";
System.out.println("stringutils output:"+StringUtils.replace(innerValue, "\'", "\'"));
System.out.println("replaceAll output:"+innerValue.replaceAll("\'", "\'"));
预期输出:
stringutils output:abc\'def\'xyz
replaceAll output:abc\'def\'xyz
实际输出:
stringutils output:abc\'def\'xyz
replaceAll output:abc'def'xyz
我只是好奇 为什么 String.replaceAll
没有用 \'
替换 '
?
不需要在String
s中对单引号进行转义(仅在char
值中),需要用替换值进行双双转义:
innerValue.replaceAll("'", "\\'")
这是由于replaceAll
将正则表达式作为参数(第二个参数必须支持反向引用的正则表达式)。
您还可以使用 replace
习语,因为您没有使用正则表达式:
innerValue.replace("'", "\'")
备注
replace
方法实际上在幕后使用 replaceAll
,但通过使用 Pattern.LITERAL
标志调用 Pattern.compile
和 Matcher.quoteReplacement
将值转换为文字在更换上。
Java 字符串包 replaceAll 方法需要 RegularExpression 作为字符串参数。 而 Commons Lang StringUtils.replace 需要字符串值。
当涉及到本机 Java 实现时,我们必须进行双重转义。 System.out.println("replaceAll output:"+innerValue.replaceAll("'", "\\'"));