← Back to Perl Course | Chapter 4: Regular Expressions | Lesson 4 of 7

Modifiers

Letters after the closing slash change how a pattern behaves.

In this page:

  1. Modifiers

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

perl
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
Common Mistakes
  1. Forgetting /i and missing uppercase matches
  2. Forgetting /m when anchoring to each line of a multi-line string
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.