[英]How to extract subjects from the email headers using regular expression in Python?
我只是開始學習正則表達式,並且在從電子郵件標題中提取主題時遇到問題。
為了只保留每個標題的主題,並且忽略“ Re:”和“ Fwd:”(不區分大小寫),我使用以下正則表達式來突出顯示所有無用的部分。
/(Subject: *)?(\bRE|FWD?)([:\[][0-9]?[ :\]]*)/ig
但是,我無法提取我想要的真實主題。
Subject: Re: re[2]: RSVP
Subject: Re: Fwd: Direct Access Application
Subject: RE:
Subject: RE: Proposed Negotiation Strategy
Subject: RE: Re: RE: Case study option
Subject: RE: Staffing
我嘗試了re.sub(...),但似乎不起作用。
這是正則表達式的另一個版本。
import re
text = [
'Subject: Re: re[2]: RSVP',
'Subject: Re: Fwd: Direct Access Application',
'Subject: RE:',
'Subject: RE: Proposed Negotiation Strategy',
'Subject: RE: Re: RE: Case study option',
'Subject: RE: Staffing'
]
p = re.compile('([\[\(] *)?.*(RE?S?|FWD?|re\[\d+\]?) *([-:;)\]][ :;\])-]*|$)|\]+ *$', re.IGNORECASE)
for line in text:
print(p.sub('', line).strip())
這將為您提供以下輸出:
RSVP
Direct Access Application
Proposed Negotiation Strategy
Case study option
Staffing
這里是解釋:
([\[\(] *)? # starting [ or (, followed by optional spaces
.*(RE|FWD|re\[\d\]?) * # Anything before RE or FW or FWD or re[number], followed by optional spaces
([-:;)\]][ :;\])-]+ $) # only count it as a Re or FWD if it is followed by
# : or - or ; or ] or ) or end of line
# (and after that you can have more of these symbols with
# spaces in between)
| # OR
\]+ *$ # match any trailing \] at end of line
# (we assume the brackets () occur around a whole Re/Fwd
# but the square brackets [] occur around the whole
# subject line)
希望這可以幫助。 謝謝
不確定這是否有幫助(我認為您的正則表達式中存在一些問題,但我無法解決),但是在Python中,您不使用/ig
傳遞標志,您可以這樣做:
re.sub('(Subject: *)?(\bRE|FWD?)([:\[][0-9]?[ :\]]*)',
subjectstring, '', flags = re.IGNORECASE)
你很親密! 您要做的就是使用捕獲組來獲得所需的匹配部分。 這是您的正則表達式略有修改:
/(?:Subject:\s*)?(?:\bRE|FWD?)(?:[:\[][0-9]?[ :\]]*)(.*)/ig
因此,您會注意到其中的3 ?:
。 這意味着這些括號內的匹配項不會被正則表達式引擎捕獲到一個組中。 但是,最后一部分將是: (.*)
最后一部分是您想要的,並且位於比賽的第一個捕獲組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.