[英]find emails in text with python and regex
我正在嘗試從文本中提取電子郵件。 我使用了re.search
,它返回了1.出現的位置,但是我繼續使用了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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.