Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a regular expression multiple times with Perl

Tags:

regex

perl

Noob question here. I have a very simple perl script and I want the regex to match multiple parts in the string

my $string = "ohai there. ohai";
my @results = $string =~ /(\w\w\w\w)/;
foreach my $x (@results){
    print "$x\n";
}

This isn't working the way i want as it only returns ohai. I would like it to match and print out ohai ther ohai

How would i go about doing this.

Thanks

like image 707
Collin O'Connor Avatar asked Jun 16 '11 15:06

Collin O'Connor


1 Answers

Would this do what you want?

my $string = "ohai there. ohai";
while ($string =~ m/(\w\w\w\w)/g) {
    print "$1\n";
}

It returns

ohai
ther
ohai

From perlretut:

The modifier "//g" stands for global matching and allows the matching operator to match within a string as many times as possible.

Also, if you want to put the matches in an array instead you can do:

my $string = "ohai there. ohai";
my @matches = ($string =~ m/(\w\w\w\w)/g);
foreach my $x (@matches) {
    print "$x\n";
}    
like image 113
dereferenced Avatar answered Oct 08 '22 06:10

dereferenced