Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

regex - Match only if not preceded or followed by a digit

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...