2014-10-10 22 views
0

我想在分隔符之間獲取數據並在匹配中包含分隔符。正則表達式匹配包含分隔符的多行文本

實施例文本:

>>> 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.

如何包含檢測報告分隔符?

回答

0

只要做到:

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

或者,如果你害怕一個文件一行一行:

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

使用正則表達式如下用分隔符來獲得數據。

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

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

DEMO

[\S\s]將匹配的一個或多個空間或非空格字符。

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> 
2

可以簡化正則表達式如下:

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

注意我用了一個不同的分隔符,以避免「傾斜牙籤綜合症」。

s修飾符使.匹配換行符。

($report)括號中強制列表上下文,所以匹配返回所有匹配的組。 $1因此被分配到$report

0
/(<detection-report>.*?<\/detection-report>)/gs 
相關問題