tags:

views:

42

answers:

2

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?

+2  A: 

You can use the find method in a loop to count. There is an example in the Java tutorial:

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.

Mark Byers
without looping can i find at one shot. because it might reduce the performance.
GK
Even if there were a function that you could call without looping, internally it would still have a loop so I don't think you would see a significant performance improvement. The first method I outlined above should give you good performance as the string is only scanned once.
Mark Byers
k.. thanks mark.
GK
+1  A: 

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++;
}
piggles
above answer is probably better.
piggles
Agreed. Firstly, your solution has to rescan from the start each time. Secondly, it will give the wrong answer if (for example) the replacement string contains something that matches the key pattern.
Stephen C
actually if one were to remove the line matcher = keyPattern.matcher(str); from the while loop, it should work, right?
piggles