Using Named Groups in Regular Expressions - Java Regular Expressions

Java examples for Regular Expressions:Group

Description

Using Named Groups in Regular Expressions

Demo Code

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

public class Main {
  public static void main(String[] args) {
    // Prepare the regular expression
    String regex = // w  w  w .  j a va  2s .  c om
      "\\b(?<areaCode>\\d{3})(?<prefix>\\d{3})(?<lineNumber>\\d{4})\\b";
    
    // Reference first two groups by names and the thrd oen as its number
    String replacementText = "(${areaCode}) ${prefix}-$3";
    
    String source = "1111111111, 1111111, and 1111111111";

    // Compile the regular expression
    Pattern p = Pattern.compile(regex);

    // Get Matcher object
    Matcher m = p.matcher(source);

    // Replace the phone numbers by formatted phone numbers
    String formattedSource = m.replaceAll(replacementText);

    System.out.println("Text: " + source);
    System.out.println("Formatted Text: " + formattedSource);
  }
}

Related Tutorials