How to use the global modifier /g in Perl regex?
Question
How to use the global modifier /g in Perl regex?
The global modifier /g in Perl regular expressions is a powerful feature that allows you to find all occurrences of a pattern in a string, rather than stopping at the first match. Understanding how /g works is essential for effectively using Perl's regex capabilities.
What does /g do?
By default, a regex match in Perl (m//) finds only the first occurrence of the pattern in the string. Adding the global modifier /g tells Perl to continue matching repeatedly throughout the string, returning every match rather than stopping after the first.
Using /g in different contexts
- Matching all occurrences with
while: Most common usage is looping over matches with/g, which maintains position between regex calls. - Matching all occurrences at once with
in list context: Usingm//gin list context returns all matches as a list. - Substitution:
s///greplaces all occurrences of a pattern in the string.
Example: Find all words starting with a capital letter
#!/usr/bin/perl
use strict;
use warnings;
my $text = "Alice and Bob went to the Market. Then Alice left.";
# Using /g with while to iterate over all matches:
while ($text =~ /([A-Z]\w*)/g) {
print "Found capitalized word: $1\n";
}
# Using /g in list context to get all matches at once:
my @words = ($text =~ /([A-Z]\w*)/g);
print "All capitalized words: @words\n";
# Using s///g to replace all occurrences:
(my $new_text = $text) =~ s/Alice/Caroline/g;
print "After substitution: $new_text\n";
Explanation of the example
- The regex
/([A-Z]\w*)/matches words starting with a capital letter. - The first loop uses
/gwith awhileloop, which remembers the position in the string across iterations and finds successive matches. - The array
@wordsshows how/gin list context returns all matches at once. - The substitution
s/Alice/Caroline/greplaces all occurrences of "Alice" with "Caroline".
Common pitfalls
- When not using a loop or list context,
/gaffects internal match position, which can cause unexpected behavior on subsequent calls if you reuse the same regex. - The
/gmodifier behaves differently on scalar vs list context, so ensure you understand context when using it. - If you want to restart matching from the beginning, reset position with
pos()or use a new string.
Summary
The global modifier /g is your go-to tool for matching multiple instances of a pattern in a string, either iteratively (with while loops), all at once (in lists), or replacing globally (with s///g). Mastering /g unlocks powerful and flexible regex operations in Perl.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 6ms
Found capitalized word: Alice
Found capitalized word: Bob
Found capitalized word: Market
Found capitalized word: Then
Found capitalized word: Alice
All capitalized words: Alice Bob Market Then Alice
After substitution: Caroline and Bob went to the Market. Then Caroline left.
(empty)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?