Java - Use Group to format or replace the matched string with another string.


To format all 10-digit phone numbers as (XXX) XXX-XXXX, where X denotes a digit.

The phone number is in three groups:

  • the first three digits,
  • the next three digits, and
  • the last four digits.

You can form a regular expression using three groups.

Then you can refer to the three matched groups by their group numbers.

The regular expression would be \b(\d{3})(\d{3})(\d{4})\b.

\b matches ten digits only at word boundaries.

The following code illustrates how you can display formatted phone numbers:


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 = "\\b(\\d{3})(\\d{3})(\\d{4})\\b";

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

    String source = "1234567890, 1234567, and 1234567890";

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

    // Start match and display formatted phone numbers
    while (m.find()) {
      System.out/*from  www .jav a 2s  .c  o  m*/
          .println("Phone: " + + ", Formatted Phone: (" + + ") " + + "-" +;


Related Topic