Inline flags and verbose mode

Intermediate · 3 min

Switch flags inside a pattern with (?i) or (?i:...), and write long patterns with spaces and comments in verbose mode. JavaScript has no x flag.

Before thisFlags: ignore case, global and multilineDotall, sticky and Unicode flagsNamed capture groups

Future Programmer · 11 min · from 7:08

Inline flags and verbose mode

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Future ProgrammerReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An inline flag is written inside the pattern: (?i)cat turns on ignore-case for the whole pattern in Python, Perl and PCRE, so a flag can travel with the pattern as a plain string.
  • A scoped flag, (?i:...), affects only the parentheses, and (?-i:...) turns a flag off inside a region. a(?i:b)c matches aBc but not ABc.
  • Put a global inline flag at the very start. Python 3.9 accepts a(?i)b but warns, and applies the flag to the whole pattern, so a(?i)b matched AB.
  • Verbose mode (re.X in Python, (?x) in Perl and PCRE) ignores whitespace and treats # as a comment, so you can lay a pattern out in lines. Match a literal space with \ or [ ], and a literal # with \# or [#].
  • JavaScript has no verbose flag and no (?i) prefix. Node 26 accepts the scoped (?i:...) form. For readability, build the regex from commented pieces with source and join.

Flags that travel with the pattern

The previous two lessons set flags from outside the pattern, as an argument or after the closing slash. That is awkward in two situations. You may be handed a pattern as a plain string, in a config file, a database column or a command-line argument, with nowhere to attach a flag. Or you may need case-insensitivity for only part of a pattern: a case-sensitive ID- prefix followed by a case-insensitive hex code.

Inline flags put the switch inside the pattern text. The syntax is (? followed by flag letters and ). Python, Perl and PCRE all have them.

Whole-pattern and scoped flags

(?i)cat          the entire pattern is case-insensitive
(?i:c)at         only the c is case-insensitive
(?-i:c)at        flag i is switched off inside the parentheses

I ran them in Python 3.9, where the global form matched CAT. For the scoped form, a(?i:b)c matched aBc and not ABc. Nesting also works: (?i:a(?-i:b)c) matched AbC and rejected ABC, because the inner group turns the case-insensitivity back off for the b. pcre2grep and Perl 5.34 gave the same results (CAT matched (?i)cat, aBc matched and ABc did not). The letters follow the flags from before: i, m, s, x, and so on. Python also took a combined (?im)^cat$ on 'dog\nCAT' and returned CAT.

Placement matters in Python 3.9. A global flag in the middle of the pattern is accepted but flagged:

re.search('a(?i)b', 'AB')
-> <re.Match object; span=(0, 2), match='AB'>
   DeprecationWarning: Flags not at the start of the expression 'a(?i)b'

That matched AB, including the A before the flag, which shows the flag applies to the whole pattern, not “from here on”. I only ran 3.9. My understanding is that newer versions turn this into an error, but I didn’t test that. Put global flags first and use the scoped form for regions.

JavaScript

For years JavaScript had no inline flags. In Node 26 the scoped form is accepted, and the global form still is not:

new RegExp('(?i)cat')    // SyntaxError: Invalid group
new RegExp('(?i:c)at')   // ok
/a(?i:b)c/.test('aBc')   // true
/a(?i:b)c/.test('ABc')   // false

I didn’t check which browsers or older Node versions have the scoped form. Treat it as available only where you have verified it.

Verbose mode: patterns you can read

A 90-character pattern on one line is a puzzle. Verbose mode (re.X or re.VERBOSE in Python, (?x) in Perl and PCRE, /x in Perl) tells the engine to ignore whitespace in the pattern and to treat # as the start of a comment. You lay the pattern out like code:

pat = re.compile(r'''
    ^(?P<year>\d{4})      # four-digit year
    -(?P<month>\d{2})     # month
    -(?P<day>\d{2})$      # day
''', re.VERBOSE)
pat.search('2026-11-23').groupdict()
# {'year': '2026', 'month': '11', 'day': '23'}

It worked as written. Since the whitespace vanishes, you have to say so when you do want a space. These all behaved as promised in Python:

re.search(r'a b',   'ab',  re.X)   # match: the space was ignored
re.search(r'a\ b',  'a b', re.X)   # match: escaped space
re.search(r'a[ ]b', 'a b', re.X)   # match: a space in a class stays
re.search(r'a\#b',  'a#b', re.X)   # match: escaped hash
re.search(r'[#]x',  '#x',  re.X)   # match: # inside a class is literal

The same layout with (?x) at the front also worked in pcre2grep -o '(?x) a b # comment' and in a Perl /x match across several lines, which printed 2026/11. Verbose mode is also the answer to the question “how do I leave a comment in a regex?” You can’t, except here.

JavaScript has no verbose flag

/x doesn’t exist in JavaScript, and (?x) is a syntax error (“Invalid group”). The next best thing is to build the regex from small named pieces and comment each one, then join them with source:

const assembled = new RegExp([
  /^/,                        // start of the string
  /(?<year>\d{4})/,           // four-digit year
  /-/,
  /(?<month>0[1-9]|1[0-2])/,  // 01 to 12
  /$/,                        // end
].map(r => r.source).join(''));
assembled.test('2026-11')   // true
assembled.test('2026-13')   // false

Each piece is checked by the parser as its own literal, and comments are ordinary JavaScript comments. The cost is that flags have to be handled on the final RegExp, and a piece with a top-level | spills into its neighbour. Joining /a|b/ and /c/ gave the source a|bc, which matches a alone. Wrap such a piece in (?:...) first.

The shell tools

On macOS, grep -E '(?i)cat' matched CAT and grep -E '(?i:b)' worked, while sed -E 's/(?i)CAT/X/' failed with repetition-operator operand invalid. The BSD tools are not consistent here. grep -i does the same job without depending on any of it.

About the video

The embedded clip is the last stretch of Future Programmer’s “Python Regular Expressions Tutorial #9: Compilation Flags”, published 10 September 2023 and 11 minutes 9 seconds long. The clip runs from 7:08 to 10:27. It covers the chapters on re.VERBOSE and combining flags. The earlier chapters on dot-all, ignore case and multiline overlap the previous lessons. The video is about Python’s flag arguments, so inline flags such as (?i) and the JavaScript workaround are not in it as far as the title and chapters show. I couldn’t read a transcript, so I can’t say whether it mentions (?x). English per its title and description.

What I did not run

Python 3.11 and later, the scoped-flag form in browsers and older Node, GNU grep, and .NET and Java inline flags.

Next

You now have most of the tools for writing patterns. The next group puts them to work inside programs, starting with matching in JavaScript.

Check yourself

  1. 01What is the difference between (?i)cat and (?i:c)at?

    (?i)cat makes the whole pattern case-insensitive, so CAT matches. (?i:c)at only makes the c case-insensitive, so Cat matches but CAT does not.

  2. 02In Python verbose mode, why does re.search(r'a b', 'a b', re.X) fail to find a match?

    Verbose mode ignores unescaped whitespace in the pattern, so a b means ab and the input a b has a space the pattern does not allow. Write a\ b or a[ ]b to match a literal space.

  3. 03What happens to # inside a character class in verbose mode?

    It stays a literal hash. In my test, re.search(r'[#]x', '#x', re.X) matched. Outside a class, an unescaped # starts a comment that runs to the end of the line.

  4. 04How would you document a long pattern in JavaScript, which has no x flag?

    Write each piece as its own regex literal with a comment beside it, then join their source strings: new RegExp([/^/, /(?<year>\d{4})/, /$/].map(r => r.source).join('')).

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark