What is the equivalent of Regex-replace-with-function-evaluation in Java 7?
Since Java 9 Matcher.replaceAll
:
Pattern.compile("\\S+").matcher("Hello World!")
.replaceAll(mr -> "" + mr.group().length());
The parameter freely named mr
is a MatchResult
, with access methods like mr.group(1)
or mr.end() - mr.start()
.
Your answer is in the Matcher#appendReplacement documentation. Just put your function call in the while loop.
[The appendReplacement method] is intended to be used in a loop together with the appendTail and find methods. The following code, for example, writes one dog two dogs in the yard to the standard-output stream:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
When allowing Java 8 you can use Lambda-Expressions, to have a JavaScript like replace:
String result = StringReplacer.replace("Hello World!", Pattern.compile("\\S+"), m -> ("" + m.group().length()));
StringReplacer.java:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringReplacer {
public static String replace(String input, Pattern regex, Function<Matcher, String> callback) {
StringBuffer resultString = new StringBuffer();
Matcher regexMatcher = regex.matcher(input);
while (regexMatcher.find()) {
regexMatcher.appendReplacement(resultString, callback.apply(regexMatcher));
}
regexMatcher.appendTail(resultString);
return resultString.toString();
}
}
Source: http://www.whitebyte.info/programming/string-replace-with-callback-in-java-like-in-javascript