正则表达式匹配多行文本,包括分隔符

时间:2014-10-10 11:06:33

标签: regex perl

我想在分隔符之间获取数据并在匹配中包含分隔符。

示例文字:

>>> Possible error is caused by the segmentation fault

provided detection report:

<detection-report>
This is somthing that already in the report.
just an example report.
</detection-report>

---------------------------------------------
have a nice day

我目前的代码是:

 if($oopsmessage =~/(?<=<detection-report>)((.|\n|\r|\s)+)(?=<\/detection-report>)/) {
     $this->{'detection_report'} = $1;
 }

它检索以下内容:

  

This is something that already in the report. just an example report.

如何同时包含检测报告分隔符?

6 个答案:

答案 0 :(得分:2)

您可以将正则表达式简化为以下内容:

my ($report) = $oopsmessage =~ m{(<detection-report>.*?</detection-report>)}s;

注意我使用了不同的分隔符来避免“倾斜牙签综合征”。

s修饰符使.与换行符匹配。

($report)强制列表上下文中的括号,因此匹配返回所有匹配的组。因此,$1已分配给$report

答案 1 :(得分:0)

只是做:

if ($oopsmessage =~ #(<detection-report>[\s\S]+?</detection-report>#) {
    $this->{'detection_report'} = $1;
}

或者,如果您逐行了解文件:

while(<$fh>) {
    if (/<detection-report>/ .. /<\/detection-report>/) {
        $this->{'detection_report'} .= $_;
    }
}

答案 2 :(得分:0)

(<detection-report>(?:(?!<\/detection-report>).)*<\/detection-report>)

尝试此操作。输入标记gs。请参阅演示。

http://regex101.com/r/xT7yD8/18

答案 3 :(得分:0)

使用以下正则表达式获取带分隔符的数据。

(<detection-report>[\S\s]+?<\/detection-report>)

组索引1包含您想要的字符串。

DEMO

[\S\s]会匹配一个或多个空格或非空格字符。

答案 4 :(得分:0)

您可以将正则表达式简化为以下内容:

if($oopsmessage =~ m#(<detection-report>.+</detection-report>)#s) {
    $this->{'detection_report'} = $1;
}

say $this->{'detection_report'};

使用修饰符s可以进行多行匹配,其中.可以是新行。使用#而不是/意味着不要使用转义斜杠进行操作。

输出:

<detection-report>
This is somthing that already in the report.
just an example report.
</detection-report>

答案 5 :(得分:0)

/(<detection-report>.*?<\/detection-report>)/gs