不以国家代码开头的 9 位数字的正则表达式,如前缀
Regex for 9-digit number that does not start from the country code like prefix
我正在尝试过滤掉特定文本中的 potential Citizen Service Numbers(荷兰语中的 BSN),这些文本也充满了荷兰语 phone 数字。 phone 号码以 +31 国家代码开头,而 BSN 号码不是。
有人可以帮我想出正则表达式来匹配任何不以 +<country-code-like-prefix><space>
开头的 9 位数字吗?
例如,在句子中:
The number is +31 713176319 and 650068168 is another one.
我想提取 650068168
,但不想提取 713176319
。这可能可以通过负前瞻来解决,但我找不到正确的解决方案。
使用负后视:
(?<!\+\d\d )\b\d{9}\b
这确保 9 位数字前面没有(“+”后跟两位数字后跟 space 字符)。
Demo.
请注意,这仅适用于国家代码为两位数的情况,如您的示例所示。要支持一位或三位数字的国家代码,事情会变得有点棘手,因为 python 不支持宽度为 non-fixed 的 Lookbehinds。但是,您可以像这样使用多个 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
我正在尝试过滤掉特定文本中的 potential Citizen Service Numbers(荷兰语中的 BSN),这些文本也充满了荷兰语 phone 数字。 phone 号码以 +31 国家代码开头,而 BSN 号码不是。
有人可以帮我想出正则表达式来匹配任何不以 +<country-code-like-prefix><space>
开头的 9 位数字吗?
例如,在句子中:
The number is +31 713176319 and 650068168 is another one.
我想提取 650068168
,但不想提取 713176319
。这可能可以通过负前瞻来解决,但我找不到正确的解决方案。
使用负后视:
(?<!\+\d\d )\b\d{9}\b
这确保 9 位数字前面没有(“+”后跟两位数字后跟 space 字符)。
Demo.
请注意,这仅适用于国家代码为两位数的情况,如您的示例所示。要支持一位或三位数字的国家代码,事情会变得有点棘手,因为 python 不支持宽度为 non-fixed 的 Lookbehinds。但是,您可以像这样使用多个 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