Named captured groups Java regular expressions

JavaObject Oriented ProgrammingProgramming

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

Example

 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.in);
      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: "+matcher.group("globalCode"));
         System.out.println("National code: "+matcher.group("nationalCode"));
         System.out.println("Phone number: "+matcher.group("number"));
      }
   }
}

Output

Enter input text:
91-08955-224558
Global code: 91
National code: 08955
Phone number: 224558
raja
Published on 13-Jan-2020 11:05:43
Advertisements