Alex Pritchard Alex Pritchard - 29 days ago 14
Java Question

Replace each occurrence matched by pattern with method called on that string

I'm trying to do something like this:

public String evaluateString(String s){
Pattern p = Pattern.compile("someregex");
Matcher m = p.matcher(s);

while(m.find()){
m.replaceCurrent(methodFoo(m.group()));
}
}


The problem is that there is no replaceCurrent method. Maybe there is an equivalent I overlooked. Basically I want to replace each match with the return value of a method called on that match. Any tips would be much appreciated!

Answer

It seems that you are looking for Matcher#appendReplacement and Matcher#appendTail.

appendReplacement will do two things:

  1. it will add to selected buffer text placed between current match and previous match (or start of string for first match),
  2. after that, it will also add replacement for matched text, which can be based on current match.

appendTail will add to buffer text placed after current match.

Pattern p = Pattern.compile("someregex");
Matcher m = p.matcher(s);

StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, methodFoo(m.group()));
}
m.appendTail(sb);

String result = sb.toString();
Comments