首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Regex检测空行为结束

Regex检测空行为结束
EN

Stack Overflow用户
提问于 2018-02-28 14:37:04
回答 1查看 1.3K关注 0票数 0

我想从一些文字中提取一个序列。

序列以Diagnostic-Code:开头,中间部分可以是任意字符,甚至是多行的字符,结尾用空行标记(之后文本继续,但这不是所需序列的一部分)。

这确实适用于开头和中间部分,但发现结尾太晚了:

代码语言:javascript
复制
(?s)Diagnostic-Code: (.+)\n\n

该字符串如下所示:

代码语言:javascript
复制
...
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不同

代码语言:javascript
复制
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组:

代码语言:javascript
复制
smtp; 550-5.1.1 The email account that you tried to reach does

java代码:

代码语言:javascript
复制
diagnosticCodePatter = Pattern.compile("(?i)diagnostic[-| ]Code: ([\\s\\S]*?[\\r\\n]{2})");
matcher = diagnosticCodePatter.matcher(message);
    if (matcher.find()) {
        diagnosticCode = matcher.group(0);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-28 14:40:05

试试这个正则表达式:

代码语言:javascript
复制
Diagnostic-Code[\s\S]*?[\r\n]{2}

点击演示

别忘了用另一个在\前面的\来逃避Java。

解释

  • Diagnostic-Code -匹配文本Diagnostic-Code
  • [\s\S]*? -匹配0+出现的任意字符(包括换行符),尽可能少
  • [\r\n]{2} -匹配两个出现的换行符或回车.
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49032049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档