Support pattern matching with lambdas

XMLWordPrintable

    • Type: Enhancement
    • Resolution: Duplicate
    • Priority: P4
    • None
    • Affects Version/s: None
    • Component/s: core-libs
    • None

      Various pattern-matching operations could be made simpler with some lambda-friendly methods.

      Examples:

      1) Extracting data from a String

      Pattern p = Pattern.compile("\d*, (\d*), (\d*)");
      for (String s : lines) {
         p.match(str, r -> System.out.println(r.group(1) + r.group(2)));
      }

      (The lambda operates on a MatchResult. It could be a Consumer or a Function. It is not invoked if the string does not match.)

      2) Getting a Stream of matches from a String

      Pattern p = Pattern.compile("(\d)*");
      lines.stream().flatMap(line -> p.findAll(line)).map(r -> r.group(1)).forEach(System.out::println);

      (The result of 'findAll' is a Stream<MatchResult>.)

      3) Performing find-replace on a String

      Pattern p = Pattern.compile("<(.*)>")
      p.replace(someString, r -> "(" + r.group(1) + ")")

      Note that all of these also make sense as methods of String.

      More discussion is here: http://mail.openjdk.java.net/pipermail/core-libs-dev/2014-November/029769.html

            Assignee:
            Paul Sandoz
            Reporter:
            Dan Smith
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: