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 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");
            System.out.println("State   : ""State"));
            System.out.println("Capital : ""Capital"));

Leave a Comment