仅当前面或后面没有数字时才匹配 [英] 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.
换句话说:
[NOT DIGIT][PHONE NUMBER][NOT DIGIT]
推荐答案
Lookahead 和 Lookbehind 将帮助您解决这些限制 - 如果它们受支持,例如
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
如果不支持,您可以用 (?:^|\D)
替换后视 (?<!\d)
.如果不支持,您可以将前瞻 (?!\d)
替换为 (?:\D|$)
.
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.
您可以在此处找到演示:https://regex101.com/r/aS8jQ8/1一个>
You can find a demo here: https://regex101.com/r/aS8jQ8/1
这篇关于仅当前面或后面没有数字时才匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!