Perl: Matching multiple patterns with a regex

Perl has regular expressions built in to the core of the language and they are very powerful. It's easy enough to find a single match with a regexp:

# Find the *first* three letter word in the string
my $str = "one two three four five six seven eight nine ten";
my @x   = $str =~ m/\b(\w{3})\b/; # ("one")

If you want to find all of the three letter words you can add the g modifier to the end of your regex to tell it to match "globally".

# Find *all* the three letter words
my $str = "one two three four five six seven eight nine ten";
my @x   = $str =~ m/\b(\w{3})\b/g; # ("one", "two", "six", "ten")

You can also iterate on your global regexp if you want to get the matches one at a time:

my $str = "one two three four five six seven eight nine ten";
my @x   = ();
while ($str =~ m/\b(\w{3})\b/g) {
    push(@x, $1);
}

print join(",", @x); # "one,two,six,ten"
Leave A Reply
All content licensed under the Creative Commons License