python - 用于从电子邮件主题中删除 "FWD"、 "RE"等的正则表达式/代码

标签 python regex email

给定一个电子邮件主题行,我想清理它,摆脱“Re:”、“Fwd”和其他垃圾。因此,例如,“[Fwd] Re: Jack and Jill's Wedding”应该变成“Jack and Jill's Wedding”。

以前肯定有人这样做过,所以我希望你能指点我经过战斗测试的正则表达式或代码。

以下是一些需要清理的示例,可在 this page 上找到.该页面上的正则表达式工作得很好,但并不完全。

Fwd : Re : Re: Many
Re : Re: Many
Re  : : Re: Many
Re:: Many
Re; Many
: noah - should not match anything
RE--
RE: : Presidential Ballots for Florida
[RE: (no subject)]
Request - should not match anything
this is the subject (fwd)
Re: [Fwd: ] Blonde Joke
Re: [Fwd: [Fwd: FW: Policy]]
Re: Fwd: [Fwd: FW: "Drink Plenty of Water"]
FW: FW: (fwd) FW:  Warning from XYZ...
FW: (Fwd) (Fwd) 
Fwd: [Fwd: [Fwd: Big, Bad Surf Moving]]
FW: [Fwd: Fw: drawing by a school age child in PA (fwd)]
Re: Fwd

最佳答案

试试这个(替换为''):

/([\[\(] *)?(RE|FWD?) *([-:;)\]][ :;\])-]*|$)|\]+ *$/igm

(如果您将每个主题作为其自己的字符串,那么您不需要 m 修饰符;这只是为了让 $ 匹配行尾,而不是只是字符串的结尾,用于多行字符串输入)。

查看实际效果 here .

正则解释:

([\[\(] *)?            # starting [ or (, followed by optional spaces
(RE|FWD?) *            # RE or FW or FWD, 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)

旗帜。

i:不区分大小写。

g:全局匹配(匹配你能找到的所有Re/Fwd)。

m:让正则表达式中的“$”匹配多行输入的行尾,而不仅仅是字符串的结尾(仅当您将所有输入主题同时输入正则表达式时才相关. 如果您每次输入一个主题,那么您可以将其删除,因为行尾字符串的结尾)。

关于python - 用于从电子邮件主题中删除 "FWD"、 "RE"等的正则表达式/代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9153629/

相关文章:

python - 使用 gmail 使用 python 发送邮件

python - cv2.waitKey(0) 阻止程序

python - 升级 Ipython 时出现问题(prompt_toolkit 不兼容)

regex - 将 tail -n 的输出重新创建到文本文件

c++ - 用于格式化 MAC 地址字符串的 Boost Regex

javascript - PHP 多个按钮和 if 语句

python - 使用Python正则表达式从点直到冒号提取子字符串

python - 如何在本地修改字典而不影响 python 中的全局变量

regex - DFA 最小化

java - 电子邮件服务的 Junit 测试