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

Provide public access to java.util.regex.Pattern.namedGroups

XMLWordPrintable

      A DESCRIPTION OF THE PROBLEM :
      Hello,

      I'd like to request some kind of public access to java.util.regex.Pattern.namedGroups - in some use-cases instance of Pattern object is passed as parameter into functions where processing depends on set of named groups defined in the pattern and are not known beforehand.
      Unfortunately current java API (as I see from latest sources https://hg.openjdk.java.net/jdk/jdk/file/49a68abdb0ba/src/java.base/share/classes/java/util/regex/Pattern.java) does not provide any legitimate way of access to list of named groups or to just check if named group exists in the pattern.

      There is ancient question on stackoverflow (https://stackoverflow.com/questions/15588903/get-group-names-in-java-regex) about how to get that functionality, and the answers are
      1. use reflection – which does not work since Java9 in that particular case
      2. parse named groups by custom code – seems to be very inefficient double-work
      3. user 3rd-party library
      To me none of these ways look appropriate.

      I recommend doing following changes in java.util.regex.Pattern class and strongly hope this will happen until next LTS java release:

      1. rename existing 'namedGroups()' -> 'namedGroupsMap()' (or any other internal name as 'namedGroups()' is most appropriate for public method mentioned below)

          Map<String, Integer> namedGroupsMap() {
              Map<String, Integer> groups = namedGroups;
              if (groups == null) {
                  namedGroups = groups = new HashMap<>(2);
              }
              return groups;
          }

      2. add following public methods

          public boolean hasGroup(String name) {
              return (namedGroups != null) && namedGroups.containsKey(name);
          }

          public Map<String, Integer> namedGroups() {
              return (namedGroups == null) ? Collections.emptyMap() : Collections.unmodifiableMap(namedGroups);
          }



            smarks Stuart Marks
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: