view raw
Marijn Marijn - 11 months ago 51
Perl Question

Perl regex multiline match without dot

There are numerous questions on how to do a multiline regex in Perl. Most of them mention the

switch that makes a dot match a newline. However, I want to match an exact phrase (so, not a pattern) and I don't know where the newlines will be. So the question is: can you ignore newlines, instead of matching them with


$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";

I can put dots in the pattern instead of spaces (
) but that does not work for the second example. I can delete all newlines as preprocessing but I would like to keep newlines that are not part of the match (as in the third example).

Desired output:

replacement text
replacement text
Keep any newlines
replacement text
of the match


It sounds like you want to change your "exact" pattern to match newlines anywhere, and also to allow newlines instead of spaces. So change your pattern to do so:

$pattern = "Match this exact phrase across newlines";
$pattern =~ s/\S\K\B/\n?/g;
$pattern =~ s/ /[ \n]/g;