我尝试使用replaceAll方法替换文本但是收到此错误
Caused by: java.util.regex.PatternSyntaxException: Illegal repetition near index 0
${rate+0.0020D2}
这是我的代码
String regExp = "\\$\\{rate[+-]\\d+(\\.\\d+)D[0-9]\\}";
String text = "${rate+0.0020D2},banana,${rate-0.4002D3},${rate+0.2003D4},${rate+bananD4},${rate+.123.415D4}";
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(text);
String match = null;
List<String> matches = new ArrayList<String>(5);
while (matcher.find()) {
int startIndex = matcher.start();
int endIndex = matcher.end();
match = matcher.group();
matches.add(match.substring(2, match.length() - 1));
}
String[] results = matches.toArray(new String[0]);
for(int i=0;i <= results.length;i++){
text.replaceAll(results[i],"<span class=\"rate\""+i+">"+results[i]+ "</span>");
}
如果我使用text.replaceAll("\\$\\{rate+0.0020D2\\}","<span class=\"rate\""+i+">"+results[i]+ "</span>");
但是我不能这样做,因为我的价值是变量。有什么解决方案吗
答案 0 :(得分:1)
您的正则表达式为${rate+0.0020D2}
。你需要逃脱它:
text.replaceAll(Pattern.quote(results[i]),"<span class=\"rate\""+i+">"+results[i]+ "</span>");