Reputation: 3709
I have this regular expression to look for phone numbers in a codebase:
\\d{3}[\.\s-]?\d{3}[\.\s-]?\d{4}\g
How can I modify this so that it will not match instances where the number is preceded or followed by a digit?
18005555555 (should not match)
80055555551 (should not match)
"8005555555" (should match)
s800-555-5555 (should match)
8005555555 (should match)
800.555.5555 (should match)
Edit: I'm not trying to "match the whole word", because it is not sufficient that the match is preceded by and followed by a space. See the 3rd example of above that should also return a match.
I want to match only instances where the match is not preceded or followed by a digit.
In others words:
[NOT DIGIT][PHONE NUMBER][NOT DIGIT]
Upvotes: 1
Views: 3441
Reputation: 8413
Lookahead and lookbehind will help you with these restrictions - if they are supported, like
/(?<!\d)\d{3}[.\s-]?\d{3}[.\s-]?\d{4}(?!\d)/g
You can replace the lookbehind (?<!\d)
with (?:^|\D)
if it is not supported. You can replace the lookahead (?!\d)
with (?:\D|$)
if it is not supported.
You can find a demo here: https://regex101.com/r/aS8jQ8/1
Upvotes: 4