我想从一些文字中提取一个序列。
序列以Diagnostic-Code:开头,中间部分可以是任意字符,甚至是多行的字符,结尾用空行标记(之后文本继续,但这不是所需序列的一部分)。
这确实适用于开头和中间部分,但发现结尾太晚了:
(?s)Diagnostic-Code: (.+)\n\n该字符串如下所示:
...
Status: 5.0.0
Diagnostic-Code: X-Postfix; test.com
*this*
*should*
*be included too*
--EA7634814EFB9.1516804532/mail.example.com
Content-Description: Undelivered Message
...-编辑
谢谢你的安威尔@古尔曼!
但是java.util.regex的行为确实与regex101.com不同
Action: failed
Status: 5.1.1
Remote-MTA: dns; gmail-smtp-in.l.google.com
Diagnostic-Code: smtp; 550-5.1.1 The email account that you tried to reach does
not exist. Please try 550-5.1.1 double-checking the recipient's email
address for typos or 550-5.1.1 unnecessary spaces. Learn more at 550 5.1.1
https://support.google.com/mail/?p=NoSuchUser u11si15276978wru.314 - gsmtp
--E8A363093CEC.1520529178/proxy03.hostname.net
Content-Description: Undelivered Message
Content-Type: message/rfc822
Return-Path: <no-reply@hostname.net>该模式与regex101上的整个多行诊断代码匹配,但java只匹配第一行为第1组:
smtp; 550-5.1.1 The email account that you tried to reach doesjava代码:
diagnosticCodePatter = Pattern.compile("(?i)diagnostic[-| ]Code: ([\\s\\S]*?[\\r\\n]{2})");
matcher = diagnosticCodePatter.matcher(message);
if (matcher.find()) {
diagnosticCode = matcher.group(0);发布于 2018-02-28 14:40:05
试试这个正则表达式:
Diagnostic-Code[\s\S]*?[\r\n]{2}别忘了用另一个在\前面的\来逃避Java。
解释
Diagnostic-Code -匹配文本Diagnostic-Code[\s\S]*? -匹配0+出现的任意字符(包括换行符),尽可能少[\r\n]{2} -匹配两个出现的换行符或回车.https://stackoverflow.com/questions/49032049
复制相似问题