Named captured groups Java regular expressions

Named capturing groups allows you to reference the groups by names. Java started supporting captured groups since SE7.


 Live Demo

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
   public static void main(String[] args) {
      Scanner sc = new Scanner(;
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "(?<globalCode>[\d]{2})-(?<nationalCode>[\d]{5})-(?<number>[\d]{6})";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      while (matcher.find()) {
         System.out.println("Global code: ""globalCode"));
         System.out.println("National code: ""nationalCode"));
         System.out.println("Phone number: ""number"));


Enter input text:
Global code: 91
National code: 08955
Phone number: 224558