Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8067973

Support pattern matching with lambdas

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Duplicate
    • Icon: P4 P4
    • None
    • None
    • 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

            psandoz Paul Sandoz
            dlsmith Dan Smith
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: