Tatt Ehian
Tatt Ehian

Reputation: 79

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.

Upvotes: 2

Views: 5257

Answers (2)

rock321987
rock321987

Reputation: 11042

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 .

EDIT

You can also use what you were using earlier (I didn't paid attention to it). You just need to access the first capturing group which can be done by using $1, $2 etc.

$x =~ s/haha\s*(.*?)\s*lolo/$1/s
               <--->
                $1

Upvotes: 2

Borodin
Borodin

Reputation: 126762

There is nothing wrong with your code, and you should disregard the answers from others who are unfamiliar with Perl

As Avinash Raj said in his comment, your regex matches your string, and all you need to do is to use the capture variable $1

use strict;
use warnings 'all';

use Data::Dump;

my $s = "haha\nhphp\nhdhd\nlolo\n";

dd $1 if $s =~ /haha(.*?)lolo/s

output

"\nhphp\nhdhd\n"

Upvotes: 5

Related Questions