Java examples for Regular Expressions:Group
Back Referencing a Group in a Replacement Text
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String regex = "\\b(\\d{3})(\\d{3})(\\d{4})\\b"; String replacementText = "($1) $2-$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 ); }// w w w .ja v a2 s . c om }