Reputation: 407
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
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
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