regex intermediate
How to use the /g modifier for global matching
Question
How do I find all matches of a pattern in a string using Perl regex?
The /g modifier enables global matching, finding all occurrences of a pattern:
use strict;
use warnings;
my $text = "The cat sat on the mat with another cat";
# Method 1: List context (get all matches)
my @matches = $text =~ /\b(\w*at)\b/g;
print "Words ending in 'at': @matches\n"; # cat sat mat cat
# Method 2: Scalar context with while loop (position tracking)
while ($text =~ /\b(\w*at)\b/g) {
print "Found '$1' at position ", pos($text), "\n";
}
# Count matches
my $count = () = $text =~ /cat/g;
print "'cat' appears $count times\n"; # 2
# Extract key-value pairs
my $data = "name=John age=30 city=NYC";
my %hash = $data =~ /(\w+)=(\w+)/g;
while (my ($k, $v) = each %hash) {
print "$k => $v\n";
}
# Global substitution
my $string = "foo bar foo baz";
$string =~ s/foo/qux/g;
print "$string\n"; # qux bar qux baz
In list context, /g returns all matches. In scalar context with a loop, it returns matches one at a time, maintaining position.
Was this helpful?
Related Questions
- How to validate email addresses using Perl regex?
- How to split a string by regex pattern in Perl?
- How to use greedy vs non-greedy quantifiers in Perl regex?
- How to match start and end of string with ^ and $ in Perl?
- How to use alternation | in Perl regex?
- How to use the qr// operator to compile regex in Perl?