Java Reference
In-Depth Information
capturing group. You can also reference the captured text in the replacement text in
the replace() method of the String object as $1, $2 , $3 , and so on, where 1, 2, 3 are
the group numbers. Table 4-22 lists all character combinations that can be used in the
replacement text to refer back to the matched text.
Table 4-22. List of Boundary Matchers Inside Regular Expressions
Characters
Replacement Text
$$
$
$&
The matched substring
$`
The portion of string that precedes the matched substring. It is a $
followed by a back quote
$'
The portion of string that follows the matched substring. It is a $
followed by a single quote
$n
Refers to the matched text for group n , where n an integer in the range
1 to 99. If group n is undefined , uses the empty String. If n is greater that
the number of groups, the result is $n
Using groups and back referencing in the replacement text, you can format 10-digit
phone numbers nnnnnnnnnn as (nnn) nnn-nnnn , as shown Listing 4-26.
Listing 4-26. Formatting 10-Digit Phone Numbers
// tendigitsphonesformatter.js
var pattern = /\b(\d{3})(\d{3})(\d{4})\b/g;
var text = "3342449999, 2229822, and 6152534734";
var replacement = "($1) $2-$3";
var formattedPhones = text.replace(pattern, replacement);
print("Phones: " + text);
print("Formatted Phones: " + formattedPhones);
Phones: 3342449999, 2229822, and 6152534734
Formatted Phones: (334) 244-9999, 2229822, and (615) 253-4734
 
 
Search WWH ::




Custom Search