java append 报错_报错咯~

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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值