Java Reference
In-Depth Information
Text: 3342449027, 2339829, and 6152534734
Formatted Text: (334) 244-9027, 2339829, and (615) 253-4734
You can also achieve the same result by using the
String
class. You do not need to use the
Pattern
and
Matcher
classes at all. The following snippet of code illustrates the same concept as above, using the
String
class instead. The
String
class uses
Pattern
and
Matcher
class internally to get the result.
// 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";
// Use replaceAll() method of the String class
String formattedSource = source.replaceAll(regex, replacementText)
Using Named Groups
Using group numbers in a big regular expression is cumbersome. Java 7 added support for named groups in regular
expressions. You can do everything with the group name as you were able to do using the group numbers in the
previous section.
•
You can name a group.
•
You can back reference groups using their names.
•
You can reference group names in replacement text.
•
You can get the matched text using the group names.
As before, you need to use a pair of parentheses to create a group. The start parenthesis is followed by a ? and a
group name placed in angle brackets. The format to define a named group is
(?<groupName>pattern)
The group name must consist of only letters and digits:
a
through
z
,
A
through
Z
, and
0
through
9
. The group
name must start with a letter. The following is an example of a regular expression that uses three named groups. The
group names are
areaCode
,
prefix
, and
lineNumber
. The regular expression is to match a 10-digit phone number.
\b(?<areaCode>\d{3})(?<prefix>\d{3})(?<lineNumber>\d{4})\b
You can use
\k<groupName>
to back reference the group named
groupName
. The area code and prefix parts in a
phone number use the same pattern. You can rewrite the above regular expression that back reference the
areaCode
group as the following:
\b(?<areaCode>\d{3})
\k<areaCode>
(?<lineNumber>\d{4})\b
You can reference a named group in a replacement text as
${groupName}
. The following snippet of code shows a
regular expression with three named groups and a replacement text referencing those three groups using their names:
String regex = "\\b(?<areaCode>\\d{3})(?<prefix>\\d{3})(?<lineNumber>\\d{4})\\b";
String replacementText = "(${areaCode}) ${prefix}-${lineNumber}";