Collin O'Connor
Collin O'Connor

Reputation: 1351

Matching a regular expression multiple times with 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

Upvotes: 12

Views: 32181

Answers (2)

user2317345
user2317345

Reputation: 1

Or you could do this

my $string = "ohai there. ohai";
my @matches = split(/\s/, $string);
foreach my $x (@matches) {
  print "$x\n";
}   

The split function in this case splits on spaces and prints

ohai
there.
ohai

Upvotes: 0

dereferenced
dereferenced

Reputation: 450

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";
}    

Upvotes: 30

Related Questions