报错咯~

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 <code>String</code> for the specified
     * <code>String</code>.
     *
     * This method produces a <code>String</code> that will work
     * as a literal replacement <code>s</code> in the
     * <code>appendReplacement</code> method of the {@link Matcher} class.
     * The <code>String</code> produced will match the sequence of characters
     * in <code>s</code> 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<s.length(); 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();
    }

  

猜你喜欢

转载自www.cnblogs.com/qyy1207/p/9584482.html
今日推荐