Java - Back Referencing a Group in a Replacement Text

Introduction

You can replace all 10-digit phone numbers by formatted phone numbers.

The Matcher class has a replaceAll() method.

$n, where n is a group number, inside a replacement text refers to the matched text for group n.

$1 refers to the first matched group.

The replacement text to replace the phone numbers will be ($1) $2-$3.

The following code illustrates the technique of referencing groups in a replacement text.

Demo

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";
    String replacementText = "($1) $2-$3";
    String source = "1234567890, 1234567, and 1234567890";

    // 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);
  }/*from   w w  w .  j  a v a  2  s . co  m*/
}

Result

Related Topic