Reputation: 4797
For the code below, what do I need to change (in my regex?) so it prints out all the instances of the regex that appear in that match in $string
?
So right now the output is just the first instance that matches the regex, but I want to print out the following 2 instances as well. I thought the /g at the end of the regex would do this.
#!/usr/bin/perl
$start = '<!--Start here-->';
$end = '<!--End now-->';
$string = "Lorem ipsum dolor sit amet, consectetur <!--Start here-->adipiscing elit. Maecenas gravida dictum erat et sollicitudin. Class aptent taciti sociosqu ad litora torquent per <!--End now-->conubia nostra, per inceptos himenaeos. <!--Start here-->Mauris ac elementum enim. <!--End now-->Etiam hendrerit accumsan sodales. Morbi mi tortor, adipiscing in interdum eu, volutpat quis neque. Aenean tincidunt ornare risus, id faucibus augue dictum ut. Nullam aliquet metus vel nibh ullamcorper ornare. Vestibulum a sapien augue. Praesent tellus nulla, congue non vestibulum eget, venenatis eu tellus. <!--Start here-->Donec varius porttitor blandit.<!--End now--> a sapien augue ipsum dolor.";
$string =~ m/(($start)(.+?)($end))/g;
print $1;
Upvotes: 0
Views: 102
Reputation: 6642
That's probably not the best way for capturing it, unless you really want the starts, the ends, the full phrase including the start and end, the contents, etc. The regex operator returns match results in list context, and you can use that to do:
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
my $start = '<!--Start here-->';
my $end = '<!--End now-->';
my $string = "Lorem ipsum dolor sit amet, consectetur <!--Start here-->adipiscing elit. Maecenas gravida dictum erat et sollicitudin. Class aptent taciti sociosqu ad litora torquent per <!--End now-->conubia nostra, per inceptos himenaeos. <!--Start here-->Mauris ac elementum enim. <!--End now-->Etiam hendrerit accumsan sodales. Morbi mi tortor, adipiscing in interdum eu, volutpat quis neque. Aenean tincidunt ornare risus, id faucibus augue dictum ut. Nullam aliquet metus vel nibh ullamcorper ornare. Vestibulum a sapien augue. Praesent tellus nulla, congue non vestibulum eget, venenatis eu tellus. <!--Start here-->Donec varius porttitor blandit.<!--End now--> a sapien augue ipsum dolor.";
my @matches = ($string =~ m/$start(.+?)$end/g);
say for @matches;
Outputs:
adipiscing elit. Maecenas gravida dictum erat et sollicitudin. Class aptent taciti sociosqu ad litora torquent per
Mauris ac elementum enim.
Donec varius porttitor blandit.
i.e. no messing around with $1 $2 $3
etc.
Upvotes: 0
Reputation: 10950
Try
my @matches = $string =~ m/(($start)(.+?)($end))/g;
To capture them all to array @matches
Upvotes: 1
Reputation: 26930
Just change the way you print the results :)
while ($subject =~ m/(($start)(.+?)($end))/g) {
print $1, "\n";
}
Upvotes: 3
Reputation: 30248
You do it in a loop:
print $1 while ($string =~ m/(($start)(.+?)($end))/g);
Upvotes: 4