不以国家代码(如前缀)开头的9位数字的正则表达式

2024-06-06 12:48:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图过滤掉特定文本中的potential Citizen Service Numbers(荷兰语的BSN),这些文本中也充满了荷兰语电话号码。电话号码以+31国家/地区代码开头,而BSN号码不以+31国家/地区代码开头

有人能帮我找到正则表达式来匹配任何不以^{开头的9位数字吗

例如,在句子中:

The number is +31 713176319 and 650068168 is another one.

我想提取650068168,但不是713176319。这可能通过消极的前瞻性解决,但我无法找到正确的解决方案


Tags: the代码文本isservice电话号码数字国家
2条回答

使用负回溯:

(?<!\+\d\d )\b\d{9}\b

这可以确保9位数字前面没有(“+”后跟两位数字和空格字符)

Demo

请注意,这仅在国家/地区代码为两位数时有效,如您的示例所示。为了支持一位或三位的国家代码,事情变得有点棘手,因为python不支持非固定宽度的lookbehind。但是,您可以像这样使用多个lookbehind:

(?<!\+\d )(?<!\+\d{2} )(?<!\+\d{3} )\b\d{9}\b

Demo

我建议在这里使用re.findall

inp = "The number is +31 713176319 and 650068168 is another one."
matches = re.findall(r'(?:^|(?<!\S)(?!\+\d+)\S+ )(\d{9})\b', inp)
print(matches)

这张照片是:

['650068168']

这里的正则表达式策略是匹配一个9位数的独立数字,当它出现在字符串的最开始,或者它前面有一个“单词”(单词在这里被松散地定义为\S+),它是而不是国家代码前缀

下面是对所用正则表达式的解释:

(?:
    ^          from the start of the string
    |          OR
    (?<!\S)    assert that what precedes is whitespace or start of the string
    (?!\+\d+)  assert that what follows is NOT a country code prefix
    \S+        match the non prefix "word", followed by a space
)
(\d{9})        match and capture the 9 digit number
\b             word boundary

相关问题 更多 >