正则表达式:匹配行和前进行直到匹配,但包括匹配前后的内容

时间:2015-05-12 05:28:34

标签: regex

我正在尝试扫描日志文件,直到 match1 出现,然后继续匹配 match1 之后的所有行,直到找到 match2 。但!我还需要在同一行的 match1 之前匹配内容, match2 之后的内容也只在同一行上匹配。

到目前为止,我在mutliline标志中使用了以下内容,但我无法弄清楚如何在匹配的受尊重线上收集前后内容。

2015-05-05 17:08:25 name: this line should not be included 2015-05-05 17:08:25 name: match1 2015-05-05 17:08:25 name: contents and stuff 2015-05-05 17:08:25 name: match2 more stuff 2015-05-05 17:08:25 name: this line should not be included

文字:

2015-05-05 17:08:25 name: match1  
2015-05-05 17:08:25 name: contents and stuff  
2015-05-05 17:08:25 name: match2 more stuff  

我想要匹配:

{"d":[{"srno":17,"party":"PARESH","dt":"11/5/2015","weight":15000.0,"timestamp":"2015-05-11T20:19:55.093"},{"srno":18,"party":"SIM","dt":"11/5/2015","weight":11000.0,"timestamp":"2015-05-11T20:21:44.177"}]}

注意:每行的开头并不总是数字,有时在预期的匹配之间会有完整的空行。

1 个答案:

答案 0 :(得分:0)

使用多行选项(大多数风格的/m(?m))和使用单行选项(/s(?s)),你可以将其与

相匹配
.*match1[\s\S]*?match2.*

测试live on regex101.com

<强>解释

.*        # Match any number of characters except newlines
match1    # Match "match1"
[\s\S]*?  # Match any number of characters including newlines, as few as possible
match2    # Match "match2"
.*        # Match the rest of the characters on that line