簡體   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