Modifiers
Letters after the closing slash change how a pattern behaves.
In this page:
Modifiers
The i modifier ignores case, g matches repeatedly, m lets ^ and $ match at each line, s lets the dot match a newline and x allows whitespace and comments inside the pattern. Modifiers can be combined, as in /gi. The x modifier is a good way to keep complicated patterns readable.
Note:
Under /x, whitespace is ignored, so write \s or [ ] when you need a literal space.
Example: Modifiers
use strict;
use warnings;
print "i: ", ("PERL" =~ /perl/i ? "match" : "no match"), "\n";
my $text = "line one\nline two\nline three";
my @starts = $text =~ /^(\w+)/mg;
print "m with g: @starts\n";
print "without s: ", ("a\nb" =~ /a.b/ ? "match" : "no match"), "\n";
print "with s: ", ("a\nb" =~ /a.b/s ? "match" : "no match"), "\n";
my $re = qr/
(\d{3}) # area code
-
(\d{4}) # number
/x;
if ("555-1234" =~ $re) {
print "area=$1 number=$2\n";
}
# Output:
# i: match
# m with g: line line line
# without s: no match
# with s: match
# area=555 number=1234
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting /i and missing uppercase matches
- Forgetting /m when anchoring to each line of a multi-line string
- Leaving spaces in a /x pattern and expecting them to match
Chapter Summary
- /i ignores case
- /m makes ^ and $ match per line
- /s lets . match a newline
- /x allows whitespace and comments
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: