Reputation: 532
I am looking for a keyword in a multiline input using a regex like this,
if($input =~ /line/mi)
{
# further processing
}
The data in the input variable could be like this,
this is
multi line text
to be matched
using perl
The code works and matches the keyword line correctly. However, I would also like to obtain the line where the pattern was matched - "multi line text" - and store it into a variable for further processing. How do I go about this?
Thanks for the help.
Upvotes: 1
Views: 4634
Reputation: 67221
Did you try his?
This works for me. $1 represents the capture of regex inside (
and )
Provided there is only one match in one of the lines.If there are matches in multiple lines, then only the first one will be captured.
if($var=~/(.*line.*)/)
{
print $1
}
If you want to capture all the lines which has the string line then use below:
my @a;
push @a,$var=~m/(.*line.*)/g;
print "@a";
Upvotes: 0
Reputation: 1256
I'd look if the match is in the multiline-String and in case it is, split it into lines and then look for the correct index number (starting with 0!):
#!/usr/bin/perl
use strict;
use warnings;
my $data=<<END;
this is line
multi line text
to be matched
using perl
END
if ($data =~ /line/mi){
my @lines = split(/\r?\n/,$data);
for (0..$#lines){
if ($lines[$_] =~ /line/){
print "LineNr of Match: " . $_ . "\n";
}
}
}
Upvotes: 0
Reputation: 91385
TLP's answer is better but you can do:
if ($input =~ /([^\n]+line[^\n]+)/i) {
$line = $1;
}
Upvotes: 0
Reputation: 67900
You can grep out the lines into an array, which will then also serve as your conditional:
my @match = grep /line/mi, split /\n/, $input;
if (@match) {
# ... processing
}
Upvotes: 3