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.