Java Reference
In-Depth Information
When you name a group, the group still gets a group number, as discussed in the previous section. You can
still refer to a group by its group number even though it has a name. The above snippet code is rewritten as follows
in which the third group, which has been named lineNumber , is referenced using its group number in as $3 in the
replacement text:
String regex = "\\b(?<areaCode>\\d{3})(?<prefix>\\d{3})(?<lineNumber>\\d{4})\\b";
String replacementText = "(${areaCode}) ${prefix}-$3";
After a successful match, you can use the group(String groupName) method of the Matcher class to get the
matched text for the group.
Listing 14-6 shows how to use group names in a regular expression and how to use the names in a replacement text.
Listing 14-6. Using Named Groups in Regular Expressions
// NamedGroups.java
package com.jdojo.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NamedGroups {
public static void main(String[] args) {
// Prepare the regular expression
String regex =
"\\b(?<areaCode>\\d{3})(?<prefix>\\d{3})(?<lineNumber>\\d{4})\\b";
// Reference first two groups by names and the thrd oen as its number
String replacementText = "(${areaCode}) ${prefix}-$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);
}
}
Text: 3342449027, 2339829, and 6152534734
Formatted Text: (334) 244-9027, 2339829, and (615) 253-4734
 
Search WWH ::




Custom Search