繁体   English   中英

如何使用Java中的replaceAll方法替换特定模式的文本?

[英]How to replace a text of particular pattern using replaceAll method in java?

嗨,我正在尝试使用replaceAll方法替换文本,该文本具有特定模式,因此首先我使用正则表达式模式找到该文本,然后在所有文本上应用replaceAll方法。 这是我的代码

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>();
while (matcher.find()) {

    int startIndex = matcher.start();
    int endIndex = matcher.end();
    match = matcher.group();
    matches.add(match.substring(2, match.length() - 1));

}

for(int i=0;i <= matches.size();i++){
text.replaceAll(Pattern.quote(matches.get(i)),Matcher.quoteReplacement("<span class=\"rate\""+i+">"+matches.get(i)+ "</span>")); 
System.out.println(text);
}

但我得到相同的输出。 谁能告诉我我在哪里做错

跳出来的事情是replaceAll 返回一个字符串,其中包含所做的更改,它不会更改您调用它的字符串(它不能,字符串是不可变的)。

所以:

text = text.replaceAll(Pattern.quote(matches.get(i)),Matcher.quoteReplacement("<span class=\"rate\""+i+">"+matches.get(i)+ "</span>"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM