我正在尝试将http://cpansearch.perl.org/src/DSTAAL/Mail-Log-Parse-1.0400/lib/Mail/Log/Parse/Postfix.pm转换为Java。
给出perl代码片段
@{$line_info{to}} = $line_info{text} =~ m/\bto=([^,]+),/g;
等同于java伪代码
if (lineInfo.getText().contains("<beginning of word or sentence>to=")) {
lineInfo.setTo(lineInfo.getText().<get text between 'to=' and comma?>);
}
有人能给我一个有用的Java示例吗?
示例输入行可能是
Apr 22 07:08:33 server postfix/smtpd[19793]: NOQUEUE: filter: RCPT from mail-eopbgr50060.outbound.protection.outlook.com[40.107.5.60]: <someone@something.co.uk>: Sender address triggers FILTER smtp-amavis:[127.0.0.1]:10024; from=<someone@something.co.uk> to=<someone2@something2.co.uk> proto=ESMTP helo=<EUR03-VE1-obe.outbound.protection.outlook.com>
我希望lineInfo.setTo()
设置为someone2@something2.co.uk
答案 0 :(得分:0)
要获取捕获组的文本,您需要使用Pattern
和Matcher
类。
Pattern p = Pattern.compile("\\bto=([^,]+),"); // remember to double the \ escape
Matcher m = p.matcher(lineInfo.getText());
List<String> list = new ArrayList<>();
while (m.find()) {
list.add(m.group(1)); // add text in capture group 1 to the list
}
lineInfo.setTo(list);
作为单一陈述,在Java 9+中,您可以使用流:
lineInfo.setTo(Pattern.compile("\\bto=([^,]+),")
.matcher(lineInfo.getText())
.results()
.map(r -> r.group(1))
.collect(Collectors.toList()));