Java - Replace String text with Regular Expressions

Introduction

The following code shows how to replace all 10-digit phone numbers by formatted phone numbers.

The String class uses Pattern and Matcher class internally to get the result.

Demo

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";

    // Use replaceAll() method of the String class
    String formattedSource = source.replaceAll(regex, replacementText);
    System.out.println(formattedSource);
  }/*from   w  w  w .j  ava2  s  .  c  o  m*/
}

Result

Related Topic