Java Reference
In-Depth Information
However, to get the first three digits (the area code), you will have to write extra code. If you form a regular expression
using groups, you can get the area code using the group number. The regular expression placing the first three digits of
a phone number in a group would be \b(\d{3})\d{7}\b . If m is the reference to a Matcher object associated with this
pattern, m.group(1) will return the first three digits of the phone number after a successful match. You can also use
m.group(0) to get the entire matched text. Listing 14-4 illustrates the use of groups in regular expressions to get the
area code part of phone numbers. Note that 2339829 does not match the pattern because it has only 7 digits.
Listing 14-4. Using Groups in Regular Expressions
// PhoneMatcher.java
package com.jdojo.regex;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class PhoneMatcher {
public static void main(String[] args) {
// Prepare a regular expression: A group of 3 digits followed by 7 digits.
String regex = "\\b(\\d{3})\\d{7}\\b";
// Compile the regular expression
Pattern p = Pattern.compile(regex);
String source = "3342449027, 2339829, and 6152534734";
// Get the Matcher object
Matcher m = p.matcher(source);
// Start matching and display the found area codes
while(m.find()) {
String phone = m.group();
String areaCode = m.group(1);
System.out.println("Phone: " + phone + ", Area Code: " + areaCode);
}
}
}
Phone: 3342449027, Area Code: 334
Phone: 6152534734, Area Code: 615
Groups are also used to format or replace the matched string with another string. Suppose you want to format all
10-digit phone numbers as (XXX) XXX-XXXX , where X denotes a digit. As you can see, the phone number is in three
groups: the first three digits, the next three digits, and the last four digits. You need to form a regular expression using
three groups so 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 . The \b in the beginning and in the end denotes that you are interested in matching ten
digits only at word boundaries. The following snippet of code illustrates how you can display formatted phone numbers:
// Prepare the regular expression
String regex = "\\b(\\d{3})(\\d{3})(\\d{4})\\b";
// Compile the regular expression
Pattern p = Pattern.compile(regex);
Search WWH ::




Custom Search