Java Reference
In-Depth Information
String source = "3342449027, 2339829, and 6152534734";
// Get Matcher object
Matcher m = p.matcher(source);
// Start match and display formatted phone numbers
while(m.find()) {
System.out.println("Phone: " + m.group() + ", Formatted Phone: (" + m.group(1) + ") " +
m.group(2) + "-" + m.group(3));
}
Phone: 3342449027, Formatted Phone: (334) 244-9027
Phone: 6152534734, Formatted Phone: (615) 253-4734
You can also replace all 10-digit phone numbers in the input text by formatted phone numbers. You have already
learned how to replace the matched text with another text using the replaceAll() method of the String class.
The Matcher class also has a replaceAll() method, which accomplishes the same. The problem you are facing in
replacing the phone numbers by the formatted phone numbers is getting the matched parts of the matched phone
numbers. In this case, the replacement text also contains the matched text. You do not know what text matches the
pattern in advance. Groups come to your rescue. $n, where n is a group number, inside a replacement text refers to the
matched text for group n. For example, $1 refers to the first matched group. The replacement text to replace the phone
numbers with the formatted phone numbers will be ($1) $2-$3. Listing 14-5 illustrates the technique of referencing
groups in a replacement text.
Listing 14-5. Back Referencing a Group in a Replacement Text
// MatchAndReplace.java
package com.jdojo.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchAndReplace {
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 = "3342449027, 2339829, and 6152534734";
// 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 );
}
}
 
Search WWH ::




Custom Search