繁体   English   中英

正则表达式-在完整日期之后和标准文本之前获取字符串

[英]Regex - get string after full date and before standard text

我被困在另一个正则表达式上。 我正在提取电子邮件数据。 在下面的示例中,仅引号中的时间,日期和消息发生更改。

Message Received 6:06pm 21st February "Hello. My name is John Smith" Some standard text.
Message Received 8:08pm 22nd February "Hello. My name is "John Smith"" Some standard text.

仅当我需要从正向后看(?<=Message Received )开始以在数据的此特定点开始搜索时,才如何获取消息? 该消息将始终以引号开头和结尾,但是用户可以像第二个示例一样插入自己的引号。

用于提取双引号之间的消息。

(?=Message Received)[^\\"]+\\K\\"[\\w\\s\\"\\.]+\\"

正则表达式演示

您将消息捕获到一个组中

(?<=Message Received)[^"]*(.*)(?=\s+Some standard text)

您可以在捕获组中使用否定的charcter类:

/Message Received.*?"([^\n]+)"/

片段:

$input = 'Message Received 6:06pm 21st February "Hello. My name is John Smith" Some standard text.
Message Received 8:08pm 22nd February "Hello. My name is "John Smith"" Some standard text.}';

preg_match_all('/Message Received.*?"([^\n]+)"/', $input, $matches);

foreach ($matches[1] as $match) {
    echo $match . "\r\n";
}

输出:

> Hello. My name is John Smith
> Hello. My name is "John Smith"

此页面上其他三个已发布答案中的两个提供了错误的结果。 其他发布的答案没有一个能像下面这样高效:

若要正确提取外部双引号之间的子字符串,请使用以下模式之一:

/Message Received[^"]+"\\K[^\\n]+(?=")/ (无捕获组,需要132个步骤, 演示

/Message Received[^"]+"([^\\n]+)"/ (捕获组,需要130个步骤, 演示

两种模式都使用导致目标子字符串(包括目标子字符串)的否定字符类提供最大的准确性和效率。 第一种模式通过使用\\K而不是捕获组将preg_match_all()的输出数组膨胀降低了50%。 由于这些原因,您的项目中应使用这些模式之一。 随着输入字符串大小的增加,与其他发布的模式相比,我的模式提供的性能越来越好。

PHP实现:

$in代表您的输入字符串。

模式1方法:

var_export(preg_match_all('/Message Received[^"]+"\K[^\n]+(?=")/',$in,$out)?$out[0]:[]);
// notice the output array only has elements in the fullstring subarray [0]

输出:

array (
  0 => 'Hello. My name is John Smith',
  1 => 'Hello. My name is "John Smith"',
)

模式2方法:

var_export(preg_match_all('/Message Received[^"]+"([^\n]+)"/',$in,$out)?$out[1]:[]);
// notice because a capture group is used, [0] subarray is ignored, [1] is used

输出:

array (
  0 => 'Hello. My name is John Smith',
  1 => 'Hello. My name is "John Smith"',
)

两种方法均提供所需的输出。


Anirudha的错误模式: /(?<=Message Received)[^"]*(.*)(?=\\s+Some standard text)/ (345个步骤+一个捕获组+包括不需要的外部双引号)

Josh Crozier的模式: /Message Received.*?"([^\\n]+)"/ (174步+一个捕获组)

Sahil Gulati的错误模式: /(?=Message Received)[^\\"]+\\K\\"[\\w\\s\\"\\.]+\\"/ (109个步骤+包括不需要的外部双引号+不必要的转义字符在模式中)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM