java - 从邮件主题中删除 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 是一件很痛苦的事情。任何帮助表示赞赏。
解决方案
您可以使用以下方法删除不仅绑定到字符串开头的事件:
\b(?:Fwd|Re)\b\h*(?::\h*)?
请注意,这也将匹配最后一个完整行Re: Fwd
IfFwd
不应匹配(因此冒号不是可选的)并绑定到字符串的开头:
^(?:(?:Fwd|Re)\h*:\h*)+
解释
^
字符串的开始(?:
非捕获组(?:Fwd|Re)\h*:\h*
在可选的水平空格之间匹配Fwd
或Re
后跟冒号
)+
关闭非捕获组并重复 1 次以上以获取所有事件
例子
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
推荐阅读
- geoserver - 重投影:wms级联还是客户端js?
- python - NiFi Parse PDF 使用 Python Tika 错误:ExecuteStreamCommand
- swift - Swift,遗传算法中的协议和泛型
- javascript - JSON中只有一个数据时返回错误的数组
- c - C - 整数输入检查
- javascript - jQuery ajax 没有将帖子数据传递到 php 页面
- java - Firestore 字段空类型用法
- r - 标签中带有长名称的ggplotly
- javascript - WebStorm addEventListener 自动完成建议
- windows - 向文件夹中的每个文件添加“空字节”?