当允许 Java 8 时,您可以使用 Lambda-Expressions 来替换 JavaScript:
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();
}
}
来源: http: //www.whitebyte.info/programming/string-replace-with-callback-in-java-like-in-javascript