我想出了一个regex表达式,这个表达式对于我查找电话号码的目的来说是非常有效的。
我想更进一步,并使用它在大文本块,以识别匹配的字符串后面的单词‘单元格’或‘移动’最多10个字符。我希望它返回Cell Phone: (954) 555-4444
和Mobile 555-777-9999
中的数字,但不返回Fax: (555) 444-6666
类似的东西(用伪码)
regex = re.compile(r'(\+?[2-9]\d{2}\)?[ -]?\d{3}[ -]?\d{4})')
bigstring = # Some giant string added together from many globbed files
matches = regex.search(bigstring)
for match in matches:
if match follows 'cell' or match follows 'mobile':
print match.group(0)
发布于 2015-03-25 18:51:10
你可以:
txt='''\
Call me on my mobile anytime: 555-666-1212
The office is best at 555-222-3333
Dont ever call me at 555-666-2345 '''
import re
print re.findall(r'(?:(mobile|office).{0,15}(\+?[2-9]\d{2}\)?[ -]?\d{3}[ -]?\d{4}))', txt)
指纹:
[('mobile', '555-666-1212'), ('office', '555-222-3333')]
发布于 2015-03-25 18:39:40
你可以用你的正则表达式来完成这个任务。在re
文档中,您会发现,只有在模式r'(?<=abc)def'
前面有'abc'
的情况下,模式才与'def'
匹配。
类似地,如果r'Hello (?=World)'
后面跟着'World'
,则匹配'Hello '
。
https://stackoverflow.com/questions/29263680
复制相似问题