user3635458 user3635458 - 5 months ago 11
Perl Question

Perl regex match string including newline

How do I match something like this:

haha\nhphp\nhdhd\nlolo\n


I want to extract between
haha
and
lolo
including the newline character, I was using the regex below but failed:

/haha(.*?)lolo/s


What I expected to be extracted:

\nhphp\nhdhd\n


I tried with the other modifiers like
//n
,
//m
, but it doesn't work.

Answer

You need (?s) modifier

$x="haha\nhphp\nhdhd\nlolo\n";
$x =~ s/(?s)haha\s*(.*?)\s*lolo/$1/;
print $x;

or lookahad and lookbehind

$x="haha\nhphp\nhdhd\nlolo\n";
$x =~ m/(?s)(?<=haha)\s*(.*?)(?=\s*lolo)/;
print $1;

NOTE :- (?s) is DOTALL modifier. It allows to matche newline with .

Comments