String replaceAll(regex, replacement)函数 , 由于第一个参数支持正则表达式,replacement中出现“$”,会按照$1$2的分组
模式进行匹配,当编译器发现“$”后跟的不是整数的时候,就会抛出“非法的组引用”的异常。
所以我们在使用replaceAll(regex, replacement)函数的时候要特别小心。
问题1: 如果replacement中带有字符 $ ,则会报错
java.lang.IllegalArgumentException: Illegal group reference
问题2: 如果replacement中带有字符 \,则会报错
java.lang.IllegalArgumentException: character to be escaped is missing
解决办法:
在执行replaceAll时,对replacement字段的值进行关键字替换
replacement = Matcher.quoteReplacement(replacement);
示例代码1:【主要】
String replacement = entry.getValue();
replacement = Matcher.quoteReplacement(replacement);
template = template.replaceAll("\\$\\{".concat(entry.getKey().trim()).concat("\\}"), replacement);
示例代码2:
private String replacePlaceholder(String sql, Object propertyValue) {
String result;
if (propertyValue != null) {
if (propertyValue instanceof String) {
result = "'" + propertyValue + "'";
} else if (propertyValue instanceof Date) {
result = "'" + DATE_FORMAT.format(propertyValue) + "'";
} else {
result = propertyValue.toString();
}
} else {
result = "null";
}
return sql.replaceFirst("\\?", Matcher.quoteReplacement(result));
}
https://github.com/abel533/Mapper/issues/30
参考:
https://stackoverflow.com/questions/11913709/why-does-replaceall-fail-with-illegal-group-reference
http://www.javacui.com/java/45.html
http://jerval.iteye.com/blog/2164227