你好,使用 python 我想在文本中捕获电话号码,但想排除 Fax 或 fax 后面的电话号码。
我使用以下正则表达式,如果句子以 Fax 或 fax 开头,它会起作用,但如果 fax 在句子中,它就不起作用:
^(?!fax|Fax)(?:.*?)(?![-a-z])((?:[^0-9])((\+|00)33\s?|0|\(0\))[123456789][ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2})(?![0-9])
这里是我分析的文本示例:
text
Adresse quai du Sa fax 06 32 32 32 33 rtel – 59100 ROUBAIX| FRANCE
faTel : 0 8 99 70 1761 – Fax : 06 32 32 32 34
Mail :support@domain.com
06 32 32 32 35
Fax 06 32 32 32 36
tel 06 32 32 32 37 henrg
我的正则表达式的结果是:
Match 1
Full match 5-42 `Adresse quai du Sa fax 06 32 32 32 33`
Group 1. 27-42 ` 06 32 32 32 33`
Group 2. 28-29 `0`
Match 2
Full match 72-117 `faTel : 0 8 99 70 1761 – Fax : 06 32 32 32 34`
Group 1. 102-117 ` 06 32 32 32 34`
Group 2. 103-104 `0`
Match 3
Full match 118-157 `Mail :support@domain.com
06 32 32 32 35`
Group 1. 142-157 `
06 32 32 32 35`
Group 2. 143-144 `0`
Match 4
Full match 178-196 `tel 06 32 32 32 37`
Group 1. 181-196 ` 06 32 32 32 37`
Group 2. 182-183 `0`
但我不想在结果中出现“06 32 32 32 34”和“06 32 32 32 33”,因为“fax”在...
谢谢
请您参考如下方法:
我建议使用正则表达式来匹配您不需要的内容,但会匹配并捕获您需要的内容:
(?i)fax\W*\d[\s\d]*|(\d[\s\d]*\d)
参见 regex demo .绿色突出显示的项目是您需要捕获的。注意:您在第 1 组中获得的号码应至少包含 2 位数字。此外,您可以根据进一步的要求精确确定模式,只需使用相同的“框架”,因为我试图简化正则表达式结构以显示主要概念。
详情
(?i)- 不区分大小写的修饰符fax-fax子串\W*- 任何 0+ 个非单词字符(您可以将其精确化为仅适用于空格和冒号,例如\s*(?::\s*)?)\d- 一个数字[\s\d]*- 0+ 个空格或数字|- 或者...(\d[\s\d]*\d)- 第1组(你需要的值)\d- 一个数字[\s\d]*- 0+ 个空格或数字\d- 一个数字
在 Python 2 中,使用
import re
rx = r"(?i)fax\W*\d[\s\d]*|(\d[ \d]*\d)"
s ="text\nAdresse quai du Sa fax 06 32 32 32 33 rtel – 59100 ROUBAIX| FRANCE\nfaTel : 0 8 99 70 1761 – Fax : 06 32 32 32 34\nMail :support@domain.com\n06 32 32 32 35\n\nFax 06 32 32 32 36\ntel 06 32 32 32 37 henrg"
res = filter(None, re.findall(rx, s))
print(res)
# => ['59100', '0 8 99 70 1761', '06 32 32 32 35', '06 32 32 32 37']
