Java-Name Capturing Groups

Name Capturing Groups

We can use name capturing groups using ?<name> in front of the regex capturing group. Then we can refer to such group using given name.

Program


Program Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("(?\\w+)\\s+(?\\w+)");
        Matcher mat = pat.matcher("TamilNadu Chennai Delhi NewDelhi");
        
        while(mat.find())
        {
            System.out.println("State   : "+mat.group("State"));
            System.out.println("Capital : "+mat.group("Capital"));
        }
    }
}

Leave a Comment