Open
Description
Original issue created by pholser on 2011-07-07 at 01:52 AM
A possible implementation:
public class Strings {
private Strings() {
throw new UnsupportedOperationException();
}
public static String replaceAll(String target, String regex, Function<MatchResult, String> operation) {
StringBuffer result = new StringBuffer(target.length() * 3 / 2);
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(target);
while (matcher.find()) {
MatchResult match = matcher.toMatchResult();
String replacement = operation.apply(match);
if (!replacement.equals(match.group()))
matcher.appendReplacement(result, replacement);
}
matcher.appendTail(result);
return result.toString();
}
}
I'm ambivalent about whether to make the type of 'regex' a Pattern or leave it as a String for the method to compile().
Motivation: To allow global replacement of matches with the result of a function of the match result, a la C#'s Regex.Replace(string, MatchEvaluator). PITA to roll the appendReplacement/appendTail bit by hand.