1、字符串替换的时候,报错了
报错信息:
java.lang.IndexOutOfBoundsException: No group 1
at java.util.regex.Matcher.start(Matcher.java:374)
at java.util.regex.Matcher.appendReplacement(Matcher.java:831)
at java.util.regex.Matcher.replaceAll(Matcher.java:906)
at java.lang.String.replaceAll(String.java:2162)
报错处的代码:
str = str.replaceAll("#VALUES#",values);
报错原因:
values是动态生成的变量,用来替换str里面的#VALUES#。但是在实际生成values的时候,有时候values带有美元符号:$
然后就报错了。
解决方法:
使用Matcher里面的方法先处理一下特殊符号:
str = str.replaceAll("#VALUES#", Matcher.quoteReplacement(values));
quoteReplacement的源码:
/**
* Returns a literal replacement String
for the specified
* String
.
*
* This method produces a String
that will work
* as a literal replacement s
in the
* appendReplacement
method of the {@link Matcher} class.
* The String
produced will match the sequence of characters
* in s
treated as a literal sequence. Slashes ('\') and
* dollar signs ('$') will be given no special meaning.
*
* @param s The string to be literalized
* @return A literal string replacement
* @since 1.5
*/
public static String quoteReplacement(String s) {
if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1))
return s;
StringBuffer sb = new StringBuffer();
for (int i=0; i
char c = s.charAt(i);
if (c == '\\') {
sb.append('\\'); sb.append('\\');
} else if (c == '$') {
sb.append('\\'); sb.append('$');
} else {
sb.append(c);
}
}
return sb.toString();
}