TExcelTAD
Home › Perl › Regex Modifiers

Regex Modifiers

Modifiers (also called flags) are letters after the closing delimiter that change how a pattern works: /i for case-insensitive, /g for global and so on. They can be combined in any order, like /gix.

Modifier Effect
/i ignore case
/g global: find all matches (or continue from the last one)
/x extended: whitespace and # comments inside the pattern are ignored
/m multi-line: ^ and $ match at the start and end of every line
/s single-line: . also matches a newline
/r (substitution only) return a new string
/e (substitution only) evaluate the replacement as code

/i: ignore case

perl · try it yourself
use strict;
use warnings;

my @answers = ("Yes", "YES", "yes please", "nope", "yEs");
for (@answers) {
    my $verdict = /^yes\b/i ? "agreed" : "declined";
    printf "%-11s %s\n", $_, $verdict;
}
Yes         agreed
YES         agreed
yes please  agreed
nope        declined
yEs         agreed

/g: global matching

In list context, /g returns every match (or every set of captures). In scalar context, each call finds the next match, and pos() tells you where the search stopped:

perl · try it yourself
use strict;
use warnings;

my $tweet = "Loving #perl and #regex today! #perl";

my @tags = $tweet =~ /#(\w+)/g;
print "Tags: @tags\n";

my %unique;
$unique{$_}++ for @tags;
print "Unique: ", join(", ", sort keys %unique), "\n";

while ($tweet =~ /#\w+/g) {
    print "Tag ends at position ", pos($tweet), "\n";
}
Tags: perl regex perl
Unique: perl, regex
Tag ends at position 12
Tag ends at position 23
Tag ends at position 36

/x: readable patterns

Long regexes quickly become unreadable. With /x, literal spaces are ignored and # starts a comment, so you can lay out a pattern over several lines. (Use \s, \ or [ ] when you really need to match a space.)

perl · try it yourself
use strict;
use warnings;

my $phone_re = qr/
    ^
    (?: \+ (?<country> \d{1,3} ) [ ] )?   # optional country code
    (?<area> \d{3} )                     # area code
    [-. ]?
    (?<number> \d{3} [-. ]? \d{4} )      # local number
    $
/x;

for my $input ("+44 020-555-0187", "555.010.4477", "12-34") {
    if ($input =~ $phone_re) {
        my $cc = $+{country} // "none";
        print "$input -> country $cc, area $+{area}, number $+{number}\n";
    } else {
        print "$input -> not a phone number\n";
    }
}
+44 020-555-0187 -> country 44, area 020, number 555-0187
555.010.4477 -> country none, area 555, number 010.4477
12-34 -> not a phone number

qr/.../ compiles a pattern into a reusable regex object that you can store in a variable, pass around and interpolate into bigger patterns.

/m and /s: multi-line text

By default ^ and $ refer to the whole string, and . does not match newlines. /m and /s change those two rules independently:

perl · try it yourself
use strict;
use warnings;

my $text = "name: Ada\nrole: engineer\nname: Linus\n";

my @without_m = $text =~ /^name: (\w+)/g;
my @with_m    = $text =~ /^name: (\w+)/mg;
print "Without /m: @without_m\n";
print "With /m: @with_m\n";

my $html = "<p>first line\nsecond line</p>";
my ($no_s) = $html =~ /<p>(.*)<\/p>/;
my ($s)    = $html =~ /<p>(.*)<\/p>/s;
print "Without /s: ", $no_s // "no match", "\n";
print "With /s: ", $s =~ s/\n/\\n/r, "\n";
Without /m: Ada
With /m: Ada Linus
Without /s: no match
With /s: first line\nsecond line

Tip: An easy way to remember: /m is about many lines for ^/$; /s treats the string as a single line, so . crosses newlines.

Inline modifiers

You can switch a modifier on for part of a pattern with (?i) or (?i:...). This is handy when a pattern comes from a variable:

perl · try it yourself
use strict;
use warnings;

my @codes = ("ERR-17", "err-17", "Err-x");
for (@codes) {
    my $ok = /^(?i:err)-\d+$/ ? "match" : "no match";
    print "$_: $ok\n";
}
ERR-17: match
err-17: match
Err-x: no match

Test yourself

Which modifier makes . match a newline?

  1. /m
  2. /s
  3. /x
  4. /n

What does my @all = $text =~ /(\d+)/g; give you?

  1. Only the first number
  2. The count of numbers
  3. A list of every number in $text
  4. true or false

What is /x used for?

  1. Faster matching
  2. Allowing whitespace and comments inside the pattern for readability
  3. Matching hexadecimal
  4. Excluding characters