2

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
Community
  • 1
  • 1
aalku
  • 2,860
  • 2
  • 23
  • 44

1 Answers1

0

You can use the built-in stream-api to achieve this.

We can do the following:

String input = "4 + 5 = 9;";

String out = input.chars()
        .mapToObj(i -> String.valueOf((char) i))
        .map(s -> s.matches("[0-9]") ? String.valueOf((Integer.parseInt(s) + 1)) : s)
        .collect(Collectors.joining());

System.out.println(out);    // prints 5 + 6 = 10;
Muhammad Hewedy
  • 29,102
  • 44
  • 127
  • 219