我正在尝试从文本中提取电子邮件。我使用了返回1.的re.search
,但后来我继续使用re.findall
。令我惊讶的是,re.findall
的电子邮件比re.search
少。可能是什么问题呢?
代码:
searchObj = re.search( r'[A-Za-z0-9._+-]+@[A-Za-z0-9]+(.|-)[A-Za-z0-9.-]+', text)
if searchObj:
mail = searchObj.group()
if mail not in emails:
emails.add(mail)
listEmails = re.findall( r'[A-Za-z0-9._+-]+@[A-Za-z0-9]+(.|-)[A-Za-z0-9.-]+', text)
for mail in listEmails:
if mail not in emails:
emails.add(mail)
用非捕捉圈或偶尔替换捕获组(.|-)
,甚至用角色类替换:
r'[A-Za-z0-9._+-]+@[A-Za-z0-9]+[.-][A-Za-z0-9.-]+'
^^^^
甚至较短:
r'[w.+-]+@[^W_]+[.-][A-Za-z0-9.-]+'
其他,re.findall
只会返回捕获值的列表。
python演示:
import re
rx = r'[w.+-]+@[^W_]+[.-][A-Za-z0-9.-]+'
s = 'some@mail.com and more email@somemore-here.com'
print(re.findall(rx, s))
# => ['some@mail.com', 'email@somemore-here.com']