Close

Java Regex - Named Capturing Groups

[Last Updated: Jan 23, 2016]

Starting from JDK 7, capturing group can be assigned an explicit name by using the syntax (?<name>X) where X is the usual regular expression.

Named captured group are useful if there are a lots of groups. They can particularly be difficult to maintained as adding or removing a group in the middle of the regex upsets the previous numbering used via Matcher#group(int groupNumber) or used as back-references (back-references will be covered in the next tutorials).

The input string section captured by named group can be retrieved by using overloaded method Matcher#group(String name)

A named capturing groups is still numbered as described in the last tutorial.

Example

Let's modify our last example to use named capturing groups.

private final static String regex =
            "\\b(?<city>[A-Za-z\\s]+),\\s(?<state>[A-Z]{2,2}):\\s(?<areaCode>[0-9]{3,3})\\b";
    private final static Pattern pattern = Pattern.compile(regex);

    public void showAreaCodes(String textData) {
        List<PhoneAreaCode> areaCodeList = getAreaCodeList(textData);
        System.out.println(areaCodeList);
    }

    public List<PhoneAreaCode> getAreaCodeList(String textData) {
        List<PhoneAreaCode> areaCodeList = new ArrayList<>();
        Matcher matcher = pattern.matcher(textData);

        while (matcher.find()) {
            if (matcher.groupCount() == 3) {
                areaCodeList.add(
                        new PhoneAreaCode(matcher.group("city"), matcher.group("state"),
                                matcher.group("areaCode")));
            }
        }
        return areaCodeList;
    }

Naming Criteria

Named capturing groups are case sensitive and only A-Z, a-z and 0-9 can be used in the name.

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.0.4

Regex Named Capturing Groups Select All Download
  • regex-named-capturing-groups
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • NamedCapturingGroupExample.java

    See Also