[英]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. 嗨,我正在尝试使用replaceAll方法替换文本,该文本具有特定模式,因此首先我使用正则表达式模式找到该文本,然后在所有文本上应用replaceAll方法。 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). 跳出来的事情是
replaceAll
返回一个字符串,其中包含所做的更改,它不会更改您调用它的字符串(它不能,字符串是不可变的)。
So: 所以:
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.