简体   繁体   中英

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

Hi I'm trying to replace a text using replaceAll method text is of a particular pattern so first of all i'm finding that text using regex Pattern and after that applying replaceAll method on all of them. here is my code

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

but i'm getting the same output. can anybody tell me where i'm doing mistake

The thing that jumps out is that replaceAll returns a string with the changes made in it, it doesn't change the string you call it on (it can't, strings are immutable).

So:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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