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

我正在尝试过滤掉特定文本中潜在的公民服务号码(荷兰语 BSN),这些文本也充满了荷兰电话号码。电话号码以 +31 国家/地区代码开头,而 BSN 号码则不然。

有人可以帮我想出正则表达式来匹配任何不以 开头的 9 位数字吗+<country-code-like-prefix><space>

例如,在句子中:

号码是+31 713176319,另一个号码是650068168。

我想提取650068168,但不提取713176319。这可能可以通过负向预测来解决,但我无法找到正确的解决方案。


慕姐8265434
浏览 223回答 2
2回答

一只斗牛犬

使用负回顾:(?<!\+\d\d&nbsp;)\b\d{9}\b这可确保 9 位数字前面没有(“+”后跟两位数字,后跟空格字符)。演示。请注意,这仅在国家/地区代码为两位数(如您的示例中所示)时才有效。要支持一位或三位数字的国家/地区代码,事情会变得有点棘手,因为 python 不支持非固定宽度的 Lookbehinds。但是,您可以像这样使用多个 Lookbehind:(?<!\+\d&nbsp;)(?<!\+\d{2}&nbsp;)(?<!\+\d{3}&nbsp;)\b\d{9}\b演示。

慕容708150

我建议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+。这是所使用的正则表达式的解释:(?:&nbsp; &nbsp; ^&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; from the start of the string&nbsp; &nbsp; |&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; OR&nbsp; &nbsp; (?<!\S)&nbsp; &nbsp; assert that what precedes is whitespace or start of the string&nbsp; &nbsp; (?!\+\d+)&nbsp; assert that what follows is NOT a country code prefix&nbsp; &nbsp; \S+&nbsp; &nbsp; &nbsp; &nbsp; match the non prefix "word", followed by a space)(\d{9})&nbsp; &nbsp; &nbsp; &nbsp; match and capture the 9 digit number\b&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;word boundary
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python