Carol
Carol

Reputation: 407

Java RegEx: Replacing a phone number (including optional parentheses)

Shouldn't this put the SPAN markers outside the phone number, not inside?

String aParagraph = "start 201-555-1212 more (301)-777-1212 again (401) 888-1212 end";
String phoneRegEx = "\\b(\\(?[1-9]{1}[0-9]{2}\\)?[- ]?[1-9]{1}[0-9]{2}-[0-9]{4})\\b";
String replaceWith = "<span>$1</span>";

aParagraph = aParagraph.replaceAll(phoneRegEx , replaceWith);

Upvotes: 1

Views: 520

Answers (2)

Ry-
Ry-

Reputation: 224904

A word boundary, \b, matches a boundary of \w+. You can just remove them:

String aParagraph = "start 201-555-1212 more (301)-777-1212 again (401) 888-1212 end";
String phoneRegEx = "(\\(?[1-9]{1}[0-9]{2}\\)?[- ]?[1-9]{1}[0-9]{2}-[0-9]{4})";
String replaceWith = "<span>$1</span>";

aParagraph = aParagraph.replaceAll(phoneRegEx, replaceWith);

Upvotes: 1

James Montagne
James Montagne

Reputation: 78650

The issue is the use of \b. It considers the first number to be the start of the word boundary, not the (. So it is actually matching:

301)-777-1212

And not

(301)-777-1212

as you intended.

Upvotes: 0

Related Questions