gpt4 book ai didi

java - 使用replaceAll方法时出现java.util.regex.PatternSyntaxException

转载 作者:行者123 更新时间:2023-11-30 08:18:42 25 4
gpt4 key购买 nike

我尝试使用 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>");,我可以解决这个问题

但我不能这样做,因为我的值是变量。有没有办法解决这个问题

最佳答案

您的正则表达式为${rate+0.0020D2}。你需要逃避它:

text.replaceAll(Pattern.quote(results[i]),"<span class=\"rate\""+i+">"+results[i]+ "</span>");

关于java - 使用replaceAll方法时出现java.util.regex.PatternSyntaxException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29295267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com