首页 > 解决方案 > 从邮件主题中删除 Re: Fwd:

问题描述

我正在尝试建立一个正则表达式以从邮件主题中删除额外的关键字,这些关键字通常由 Fwd、Re: 等邮件作曲家添加,但无法提出一个能够满足所有这些场景的正则表达式。

Fwd : Re : Re: Many
Re : Re: Many
Re:    Re: Many
Re: Many
Re: Many
RE: Presidential Ballots for Florida
RE: (no subject)
Request - should not match anything
this is the subject
Re: Fwd

我在Java中尝试了这个正则表达式:

subject.replaceAll("^.{0,3}:\s", "");

但这只会删除找到的第一个匹配项。任何正则表达式,如果它可以满足大多数常见场景,并非以上所有内容也会有很大帮助。我为 Python 找到了一些正则表达式,但是将它们转换成 Java 是一件很痛苦的事情。任何帮助表示赞赏。

标签: javaregex

解决方案


您可以使用以下方法删除不仅绑定到字符串开头的事件:

\b(?:Fwd|Re)\b\h*(?::\h*)?

正则表达式演示

请注意,这也将匹配最后一个完整行Re: Fwd


IfFwd不应匹配(因此冒号不是可选的)并绑定到字符串的开头:

^(?:(?:Fwd|Re)\h*:\h*)+

解释

  • ^字符串的开始
  • (?:非捕获组
    • (?:Fwd|Re)\h*:\h*在可选的水平空格之间匹配FwdRe后跟冒号
  • )+关闭非捕获组并重复 1 次以上以获取所有事件

正则表达式演示| Java 演示

例子

String regex = "^(?:(?:Fwd|Re)\\h*:\\h*)+";
String string = "Fwd : Re : Re: Many\n"
     + "Re : Re: Many\n"
     + "Re:    Re: Many\n"
     + "Re: Many\n"
     + "Re: Many\n"
     + "RE: Presidential Ballots for Florida\n"
     + "RE: (no subject)\n"
     + "Request - should not match anything\n"
     + "this is the subject\n"
     + "Re: Fwd";

Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(string);
String result = matcher.replaceAll("");

System.out.println(result);

输出

Many
Many
Many
Many
Many
Presidential Ballots for Florida
(no subject)
Request - should not match anything
this is the subject
Fwd

推荐阅读