ZetCode

Perl regex modifiers

last modified November 25, 2026 Perl 5.44

Regex modifiers change how a pattern is interpreted without changing its text. They are single letters written after the closing delimiter, as in /perl/i, and several of them can be combined. They can also be switched on inside the pattern. This article covers the modifiers that change the matching rules. The /g modifier is covered in Perl global matching, and /e and /r in Perl substitution.

Case-insensitive matching with /i

The /i modifier makes the pattern ignore the difference between upper and lower case letters.

case_i.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @langs = qw(Perl PERL perl Python pearl);

for my $lang (@langs) {
    my $plain = $lang =~ /^perl$/  ? 'yes' : 'no';
    my $nocase = $lang =~ /^perl$/i ? 'yes' : 'no';

    printf "%-7s plain: %-3s /i: %s\n", $lang, $plain, $nocase;
}

Without the modifier, only the lower-case word matches. With /i, all three spellings of Perl match. Words with different letters, such as pearl, still do not match.

$ perl case_i.pl
Perl    plain: no  /i: yes
PERL    plain: no  /i: yes
perl    plain: yes /i: yes
Python  plain: no  /i: no
pearl   plain: no  /i: no

Multi-line anchors with /m

Normally, ^ matches only at the start of the string and $ only at its end or before a final newline. The /m modifier makes them match at the start and end of every line inside the string.

multiline.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $text = "error: disk full\nok: backup done\nerror: no network\n";

my @first = $text =~ /^error: (.+)$/g;
say "without /m: @first";

my @all = $text =~ /^error: (.+)$/mg;
say "with /m:    ", join ' | ', @all;

my $count = () = $text =~ /^ok/mg;
say "lines starting with ok: $count";

Without /m, the pattern can only start at the beginning of the string. There, .+ stops at the first newline, which is not the end of the string, so $ fails and nothing is found. With /m, the pattern finds both error lines. The last statement counts the lines that start with ok. Assigning the matches to an empty list () and the result to a scalar gives the number of matches.

$ perl multiline.pl
without /m: 
with /m:    disk full | no network
lines starting with ok: 1

Matching newlines with /s

The dot matches any character except a newline. The /s modifier lets it match newlines too, so a pattern can span several lines.

dotall.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $html = "<p>first line\nsecond line</p>";

if ($html =~ /<p>(.*)<\/p>/) {
    say "without /s: $1";
} else {
    say "without /s: no match";
}

if ($html =~ /<p>(.*)<\/p>/s) {
    say "with /s:    $1";
}

The paragraph element contains a newline. Without /s, the .* cannot cross it and the match fails. With /s, both lines are captured. The names of the two modifiers are confusing, but they are independent: /m changes the anchors and /s changes the dot.

$ perl dotall.pl
without /s: no match
with /s:    first line
second line

Readable patterns with /x

With /x, whitespace in the pattern is ignored and # starts a comment that runs to the end of the line. A longer pattern can then be spread over several lines and documented.

extended.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $date = qr/
    ^
    (\d{4})    # year
    -
    (\d{2})    # month
    -
    (\d{2})    # day
    $
/x;

for my $s ('2026-11-25', '2026-11-5', 'today') {
    if (my ($y, $m, $d) = $s =~ $date) {
        say "$s: year $y, month $m, day $d";
    } else {
        say "$s: not a date";
    }
}

Each part of the date pattern is on its own line with a comment. The pattern is stored with qr and used in list context, so a successful match returns the three captured parts. A day without a leading zero does not match \d{2}.

$ perl extended.pl
2026-11-25: year 2026, month 11, day 25
2026-11-5: not a date
today: not a date

Spaces under /x and /xx

Because /x ignores whitespace, a space that should be matched must be escaped or put in a character class. The /xx modifier, added in Perl 5.26, goes one step further and also ignores spaces and tabs inside character classes.

extended2.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $name = 'Lucia Novak';

say "/x, plain space:   ", ($name =~ /^\w+ \w+$/x     ? 'match' : 'no match');
say "/x, escaped space: ", ($name =~ /^\w+ \  \w+$/x  ? 'match' : 'no match');
say "/x, [ ] class:     ", ($name =~ /^\w+ [ ] \w+$/x ? 'match' : 'no match');

my $hex = '3f a0 ff';

say "/x,  [0-9a-f ]:     ", ($hex =~ /^[0-9a-f ]+$/x  ? 'match' : 'no match');
say "/xx, [0-9a-f ]:     ", ($hex =~ /^[0-9a-f ]+$/xx ? 'match' : 'no match');
say "/xx, [ 0-9 a-f \\ ]: ", ($hex =~ /^[ 0-9 a-f \ ]+$/xx ? 'match' : 'no match');

Under /x, the plain space in the first pattern is ignored, so the pattern looks for two words without a space between them. An escaped space \ or a class [ ] matches a real space. Inside a class, /x keeps the space, but /xx drops it. Then the space between the hex numbers is no longer allowed. With /xx, a class can be laid out with spaces, and a space to match must be escaped.

$ perl extended2.pl
/x, plain space:   no match
/x, escaped space: match
/x, [ ] class:     match
/x,  [0-9a-f ]:     match
/xx, [0-9a-f ]:     no match
/xx, [ 0-9 a-f \ ]: match

Groups without captures with /n

Parentheses group parts of a pattern and capture the text they match. When only the grouping is needed, the /n modifier, added in Perl 5.22, turns all unnamed groups into non-capturing ones.

nocapture.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $s = 'width=640 height=480';

my @groups = $s =~ /(width|height)=(\d+)/;
say "plain: @groups";

@groups = $s =~ /(width|height)=(?<size>\d+)/n;
say "/n:    @groups";
say "named group: $+{size}";

@groups = $s =~ /(?:width|height)=(\d+)/;
say "(?:):  @groups";

In the plain pattern, the alternation group captures the name of the dimension, although we only need the number. With /n, that group no longer captures. Named groups are not affected by /n, so the size is still captured. The last pattern does the same for a single group with the (?:...) syntax.

$ perl nocapture.pl
plain: width 640
/n:    640
named group: 640
(?:):  640

ASCII rules with /a

In Perl, \d matches digits from every script in Unicode and \w matches letters of every alphabet. That is right for text, but not when validating numbers or identifiers. The /a modifier restricts \d, \w, \s and the POSIX classes to ASCII.

ascii.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;
use utf8;

binmode STDOUT, ':encoding(UTF-8)';

my @inputs = ('42', '٤٢', 'user_1', 'čaj');

for my $s (@inputs) {
    my $digits = $s =~ /^\d+$/  ? 'yes' : 'no';
    my $ascii  = $s =~ /^\d+$/a ? 'yes' : 'no';
    my $word   = $s =~ /^\w+$/  ? 'yes' : 'no';
    my $aword  = $s =~ /^\w+$/a ? 'yes' : 'no';

    printf "%-7s \\d: %-3s \\d/a: %-3s \\w: %-3s \\w/a: %s\n",
        $s, $digits, $ascii, $word, $aword;
}

The second string contains Arabic-Indic digits. They are digits for plain \d, but not under /a, and /a does the same for the Slovak letter č and \w. The source is UTF-8, so use utf8 decodes the strings, and binmode encodes the output. Unicode in regular expressions is covered in Perl regex Unicode properties.

$ perl ascii.pl
42      \d: yes \d/a: yes \w: yes \w/a: yes
٤٢      \d: yes \d/a: no  \w: yes \w/a: no
user_1  \d: no  \d/a: no  \w: yes \w/a: yes
čaj     \d: no  \d/a: no  \w: yes \w/a: no

Inline modifiers

A modifier can also be switched on inside the pattern. (?i) turns on case-insensitive matching for the rest of the enclosing group, and (?-i) turns it off again. The form (?i:...) applies the modifier only to the group it encloses.

inline.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my @lines = ('ERROR in Module', 'error in module', 'Error in MODULE');

for my $line (@lines) {
    my $whole  = $line =~ /(?i)error in module/ ? 'yes' : 'no';
    my $scoped = $line =~ /(?i:error) in Module/ ? 'yes' : 'no';
    my $off    = $line =~ /(?i)error in (?-i)module/ ? 'yes' : 'no';

    printf "%-16s (?i): %-3s (?i:): %-3s (?-i): %s\n",
        $line, $whole, $scoped, $off;
}

The first pattern ignores case entirely. In the second one, only the word error is case-insensitive, while in Module must match exactly. In the third one, case is ignored until (?-i), so module must be in lower case. Inline modifiers let different parts of a pattern follow different rules.

$ perl inline.pl
ERROR in Module  (?i): yes (?i:): yes (?-i): no
error in module  (?i): yes (?i:): no  (?-i): yes
Error in MODULE  (?i): yes (?i:): no  (?-i): no

Modifiers in qr objects

A pattern compiled with qr keeps its modifiers. When it is interpolated into a larger pattern, its modifiers apply only to its own part.

qr_flags.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $lang = qr/perl/i;

say "pattern: $lang";

for my $s ('PERL 5', 'Perl 5', 'perl 7') {
    my $result = $s =~ /^$lang 5$/ ? 'match' : 'no match';
    say "$s: $result";
}

my $loud = qr/version/;
say "inner flags win: ", ('VERSION' =~ /$loud/i ? 'match' : 'no match');

The printed pattern shows how this works. qr wraps the pattern in a group with inline modifiers. The ^ resets the defaults, u means Unicode rules and i comes from our modifier. The word Perl therefore matches in any case, while the rest of the outer pattern is unchanged. In the opposite direction, an outer /i does not reach into a qr object compiled without it. See also Perl qr//.

$ perl qr_flags.pl
pattern: (?^ui:perl)
PERL 5: match
Perl 5: match
perl 7: no match
inner flags win: no match

Best practices

These recommendations help to use regex modifiers safely and clearly.

Source

perlre: Modifiers · perlre: inline modifiers

In this article we have covered the /i, /m, /s, /x, /xx, /n and /a modifiers, inline modifiers and modifiers kept in qr objects. See also Perl regex.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.