i have the following code
我有以下代码
Pattern keyPattern = Pattern.compile(key);
Matcher matcher = keyPattern.matcher(str);
return matcher.replaceAll(value);
this will replaces the key in the str with value; but i want to know how many instances of key's has been replaced with value. so how to know that?
这将用str替换str中的键;但我想知道有多少个密钥实例被替换为值。那怎么知道呢?
2 个解决方案
#1
2
You can use the find method in a loop to count. There is an example in the Java tutorial:
您可以在循环中使用find方法进行计数。 Java教程中有一个例子:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MatcherDemo {
private static final String REGEX = "\\bdog\\b";
private static final String INPUT = "dog dog dog doggie dogg";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
int count = 0;
while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
}
}
While you are calling find, you can at the same time collect the parts of the string and manually build the result in a StringBuffer. Or if performance is not an issue, you can first count and then afterwards scan the string again with replaceAll.
当您调用find时,您可以同时收集字符串的部分并在StringBuffer中手动构建结果。或者,如果性能不是问题,您可以先计算,然后再使用replaceAll扫描字符串。
#2
1
instead you could do:
相反,你可以这样做:
int num = 0;
Pattern keyPattern = Pattern.compile(key);
Matcher matcher = keyPattern.matcher(str);
while(matcher.find()){
str = matcher.replaceFirst();
matcher = keyPattern.matcher(str); //don't know if this line is necessary
num++;
}
#1
2
You can use the find method in a loop to count. There is an example in the Java tutorial:
您可以在循环中使用find方法进行计数。 Java教程中有一个例子:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MatcherDemo {
private static final String REGEX = "\\bdog\\b";
private static final String INPUT = "dog dog dog doggie dogg";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
int count = 0;
while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
}
}
While you are calling find, you can at the same time collect the parts of the string and manually build the result in a StringBuffer. Or if performance is not an issue, you can first count and then afterwards scan the string again with replaceAll.
当您调用find时,您可以同时收集字符串的部分并在StringBuffer中手动构建结果。或者,如果性能不是问题,您可以先计算,然后再使用replaceAll扫描字符串。
#2
1
instead you could do:
相反,你可以这样做:
int num = 0;
Pattern keyPattern = Pattern.compile(key);
Matcher matcher = keyPattern.matcher(str);
while(matcher.find()){
str = matcher.replaceFirst();
matcher = keyPattern.matcher(str); //don't know if this line is necessary
num++;
}