I have a String like this "4 + 5 = 9;"
and I want to add one to each number found.
I want to use regular expressions and a transformation function for every match.
I know how to do it in Java <= 7. It is in the javadoc and in this answer.
I want to know if there is something new about this in Java 8.
EDIT: This is my best try:
private static String regexTransform(String regex, String input,
Function<String, String> function) {
Matcher m = Pattern.compile(regex).matcher(input);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, function.apply(m.group()));
}
m.appendTail(sb);
return sb.toString();
}
String res = regexTransform("[0-9]+", "4 + 5 = 9;", s-> String.valueOf(Long.parseLong(s) + 1));
System.out.println(res); // 5 + 6 = 10