【发布时间】:2016-05-24 13:53:08
【问题描述】:
关于如何在 Perl 中执行多行正则表达式有很多问题。他们中的大多数都提到了使点匹配换行符的s 开关。但是,我想匹配一个确切的短语(所以,不是模式),我不知道换行符在哪里。所以问题是:你能忽略换行符,而不是将它们与.匹配吗?
MWE:
$pattern = "Match this exact phrase across newlines";
$text1 = "Match\nthis exact\nphrase across newlines";
$text2 = "Match this\nexact phra\nse across\nnewlines";
$text3 = "Keep any newlines\nMatch this exact\nphrase across newlines\noutside\nof the match";
$text1 =~ s/$pattern/replacement text/s;
$text2 =~ s/$pattern/replacement text/s;
$text3 =~ s/$pattern/replacement text/s;
print "$text1\n---\n$text2\n---\n$text3\n";
我可以在模式中放置点而不是空格 ("Match.this.exact.phrase"),但这不适用于第二个示例。我可以删除所有换行符作为预处理,但我想保留不属于匹配的换行符(如第三个示例所示)。
期望的输出:
replacement text
---
replacement text
---
Keep any newlines
replacement text
outside
of the match
【问题讨论】:
-
大多数时候,您将换行符视为空格。然后有一次你想忽略它。做任何一个都很容易。两者都做几乎是不可能的。
标签: regex perl multiline exact-match