gpt4 book ai didi

java - 正则表达式检测空行作为结束

转载 作者:行者123 更新时间:2023-12-01 19:57:40 26 4
gpt4 key购买 nike

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

序列以 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
...

---------编辑---------

感谢您的回答@Gurman!

但是 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 does

java代码:

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

最佳答案

尝试这个正则表达式:

Diagnostic-Code[\s\S]*?[\r\n]{2}

<强> Click for Demo

在 Java 中,不要忘记在 \ 前面加上另一个 \ 进行转义。

说明

  • Diagnostic-Code - 匹配文本Diagnostic-Code
  • [\s\S]*? - 匹配任意字符(包括换行符)出现 0 次以上,尽可能少
  • [\r\n]{2} - 匹配 2 次出现的换行符或回车符。

关于java - 正则表达式检测空行作为结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49032049/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com