Flags: ignore case, global and multiline

Intermediate · 10 min

What the i, g and m flags change, why a global regex remembers lastIndex between calls, and how Python spells the same ideas with re.I and re.M instead of g.

Before thisAnchors and line boundariesQuantifiers: star, plus and question

LearnAwesome · 21 min · from 4:12

Flags: ignore case, global and multiline

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

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

What you'll learn

  • Flags change how the whole pattern behaves without changing what you wrote. In JavaScript they come after the closing slash, /cat/gi, or as the second argument to new RegExp.
  • i ignores case. g makes match, replace and matchAll work on every match instead of only the first. m makes ^ and $ match at every line break, not only at the ends of the string.
  • A regex with g or y keeps state in lastIndex. Calling test twice on the same g regex can return true then false for the same text, because the second call starts where the first stopped.
  • matchAll and replaceAll throw a TypeError if the regex lacks the g flag. Flag order does not matter, and an unknown or repeated flag is a SyntaxError.
  • Python has no g. findall and sub already work on all matches, and sub takes count=1 to stop early. Python spells the other flags re.I and re.M, or (?i) and (?m) inside the pattern.

The same pattern, played by different rules

Patterns have a built-in set of rules: matching is case-sensitive, it stops at the first match, and ^ means the start of the whole string. Sometimes you need different rules without rewriting the pattern. Searching a log for error should find Error and ERROR. Replacing a word should replace it everywhere. Checking each line of a pasted block should treat each line as its own thing.

Flags are switches on the pattern as a whole. They are the settings, and the pattern is the document. In JavaScript they go after the closing slash, /cat/gi, or as a second argument, new RegExp('cat', 'gi'). This lesson covers the three you reach for first.

i: ignore case

/cat/.test('Cat')       // false
/cat/i.test('Cat')      // true
/[a-z]+/i.exec('ABC def')[0]   // 'ABC'

With i, a letter in the pattern matches both cases, and a range like [a-z] covers capitals too. In Python the flag is re.I (or re.IGNORECASE), passed as a third argument: re.search('cat', 'Cat', re.I) matched, and so did the inline form (?i)cat. On the command line it’s grep -i: on a three-line file with Cat, cat and CAT, grep -c cat counted 1 and grep -ci cat counted 3. The next lessons return to what i does with non-ASCII letters.

g: every match, not just the first

Without g, JavaScript stops at the first match:

const s = 'a1 b22 c333';
s.match(/\d+/)               // [ '1', index: 1, input: 'a1 b22 c333', ... ]
s.match(/\d+/g)              // [ '1', '22', '333' ]
s.replace(/\d+/, '#')        // 'a# b22 c333'
s.replace(/\d+/g, '#')       // 'a# b# c#'

Two methods refuse to work at all without it. s.matchAll(/\d+/) threw TypeError: String.prototype.matchAll called with a non-global RegExp argument, and replaceAll threw the same kind of error. The language refuses rather than guess: asking for “all” with a regex that stops at one looks like a mistake.

Python has no g. The functions decide: re.findall(r'\d+', s) returned all three numbers, and re.sub(r'\d+', '#', s) replaced all three. To get the single-replace behaviour you pass a limit, count=1, which produced a# b22 c333. In sed, s/a/b/ changes the first a on a line and s/a/b/g all of them. I checked with a a a: b a a and b b b.

The trap: a global regex remembers where it stopped

A regex object with g carries state. The property lastIndex records where the next search will begin, and test and exec both use it and update it:

const re = /a/g;
re.test('aa'), re.lastIndex   // true 1
re.test('aa'), re.lastIndex   // true 2
re.test('aa'), re.lastIndex   // false 0

The third call failed because the search started at index 2, past the end, and a failure resets lastIndex to 0. This is how you walk through a string with exec in a loop. On a1 b22 c333, a while loop gave 1 at index 1 with next lastIndex 2, then 22 at 4 (next 6), then 333 at 8 (next 11).

But it bites when you reuse one global regex on separate strings. ['a','a','a'].map(x => r.test(x)) with r = /a/g returned [ true, false, true ], even though every input is the same. The same array with r = /a/ (no g) returned [ true, true, true ]. If you only want a yes-or-no answer, don’t add g. If you must keep a global regex, set re.lastIndex = 0 before each use. The matching-in-JavaScript lesson later in this group builds on this.

m: every line is its own string

By default ^ is the start of the string and $ is the end of the string. With m, they also match at every line break:

const t = 'one\ntwo\nthree';
/^two/.test(t)      // false
/^two/m.test(t)     // true
/one$/.test(t)      // false
/one$/m.test(t)     // true
t.match(/^\w+$/gm)  // [ 'one', 'two', 'three' ]
t.match(/^\w+$/g)   // null

Without m, ^\w+$ has to span the whole string, and the newlines make that impossible, so the last line returned null. With both g and m, each line matches separately. Python’s flag is re.M: re.findall(r'^\w+$', t, re.M) returned all three words, and without it, an empty list. This mirrors how grep works, since it sees one line at a time.

Combining and checking flags

Order doesn’t matter: /a/gi.flags, /a/ig.flags both printed gi, and /a/mgi.flags printed gim, always sorted. Each flag has a property too, such as .global, .ignoreCase and .multiline. A bad flag fails at construction: new RegExp('a', 'z') and new RegExp('a', 'gg') both threw SyntaxError: Invalid flags supplied to RegExp constructor. In Python you combine flags with |, re.I | re.M, which printed as re.IGNORECASE|re.MULTILINE.

About the video

The embedded clip is a section of LearnAwesome’s “Learn Regex Flags – Global, Case-Insensitive, Multiline & More Explained | Regex Tutorial”, published 3 August 2024 and 21 minutes 18 seconds long. The clip runs from 4:12 to 13:54 and covers the chapters on the global flag, the indices flag, ignore case, dot-all and multiline, each with a regex101 demo. The d (indices) and s (dot-all) chapters sit inside the clip but belong to the next lesson, which also uses this video for its later chapters. The chapters mention JavaScript, Python and PHP use. I couldn’t read a transcript, so I can’t say whether it explains lastIndex. The chapter list shows “Global (g) flag usage in JavaScript” but no named lastIndex section. English per its title and description.

What I did not run

regex101’s flag panel, PHP, and the g-style flags in editors like VS Code’s find box.

Next

Three more flags change what . matches, where a search must begin and how text is counted. Dotall, sticky and Unicode flags covers s, y, u, v and d.

Check yourself

  1. 01Why does a g regex return true, false, true for three test calls on the string a?

    After a successful test, lastIndex moves past the match. The next call starts at index 1, finds nothing in a one-character string, returns false, and resets lastIndex to 0. The third call then starts clean.

  2. 02What is the difference between /^two/ and /^two/m on the text 'one\ntwo\nthree'?

    Without m, ^ matches only at the very start of the string, so it returns false. With m, ^ also matches after each newline, so it returns true.

  3. 03'a1 b22 c333'.match(/\d+/g) returns ['1', '22', '333']. What does it return without g?

    A single match object for the first run only, with 1 in slot zero, plus index and input properties. Without g, match behaves like exec.

  4. 04How do you replace only the first match in Python, and how do you replace every match in JavaScript?

    Python: re.sub(pattern, repl, text, count=1). JavaScript: add the g flag, text.replace(/pattern/g, repl), or call replaceAll with a global regex.

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