Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - 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 =~ /(wwww)/;
foreach my $x (@results){
    print "$x
";
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Would this do what you want?

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

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/(wwww)/g);
foreach my $x (@matches) {
    print "$x
";
}    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...