Replacing with regex

Intermediate · 19 min

Rewrite text with replace, $1, $<name> and $&, replacer functions, and Python re.sub with \1 and callables. Includes the $-in-user-text trap.

Before thisCapturing groups and numberingNamed capture groupsMatching in JavaScript

The Coding Train · 19 min

Replacing with regex

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

Taught by The Coding TrainReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Without g, replace changes only the first match. With g it changes every match. replaceAll with a string replaces every occurrence, and with a regex it demands g.
  • In a JavaScript replacement string, $1 is a group, $<name> a named group, $& the whole match, $` the text before it, $' the text after it, and $$ a literal dollar sign. $0 is not special.
  • A function replacer receives (match, group1, group2, ..., offset, string, groups) and returns the new text. It is the right tool for arithmetic, case changes and any lookup.
  • Python's re.sub uses \1, \g<1> and \g<name> in the replacement string, or a callable that takes the match object. Python has no $ syntax, and a bad group reference raises re.error.
  • A replacement string is parsed, so user text containing $& or \1 gets reinterpreted. Pass a function that returns the text to insert it literally.

From finding to rewriting

Finding text answers a question. The real jobs are usually edits: swap first and last names, reformat dates, strip tags, double every number. Regex replace is a find and a template combined: the pattern says what to find, and the replacement says what to put there, with the ability to reuse pieces of what was found.

The basics, and the g flag again

const s = 'Ada Lovelace, Grace Hopper';
s.replace(/(\w+) (\w+)/, '$2 $1')    // 'Lovelace Ada, Grace Hopper'
s.replace(/(\w+) (\w+)/g, '$2 $1')   // 'Lovelace Ada, Hopper Grace'

Without g, only the first match changes. With it, both names flip. replaceAll is the explicit version. With a string pattern it replaces every occurrence, and with a regex it needs g: 'a.b.c'.replaceAll('.', '-') returned a-b-c, and plain 'a.b.c'.replace('.', '-') returned a-b.c, since a string pattern replaced only the first one, literally, with no regex dot involved.

The tokens in a replacement string

The replacement is not a regex, but it has a few special tokens. I tried each on 'cat' with the pattern /a/:

'[$&]'  -> c[a]t     $&  the whole match
'[$`]'  -> c[c]t     $`  the text before the match
"[$']"  -> c[t]t     $'  the text after the match
'$$'    -> c$t       $$  a literal dollar sign

And with groups, $1, $2 and so on refer to numbered groups and $<name> to named ones:

'2026-11-23'.replace(/(?<y>\d+)-(?<m>\d+)-(?<d>\d+)/, '$<d>.$<m>.$<y>')
// '23.11.2026'

Edge cases I tested: $0 is not special (it stayed as the literal text $0), and neither is a reference to a group that doesn’t exist. 'a'.replace(/(a)/, '$2') returned $2. With only one group, '$10' was read as $1 followed by 0, giving a0. A named reference with a name that doesn’t exist, $<y> on a pattern with only x, expanded to an empty string, with no error. And a backslash means nothing here: 'ab'.replace(/(a)/, '\\1') produced the literal text \1b. Backslash-number is a pattern syntax, not a replacement syntax, in JavaScript.

A function does the work when a template isn’t enough

When you need arithmetic, case changes or a lookup, pass a function. It is called once per match, and its return value becomes the replacement:

'price: 5 and 12'.replace(/\d+/g, n => '$' + (n * 1.5).toFixed(2))
// 'price: $7.50 and $18.00'
'hello big world'.replace(/\b\w/g, c => c.toUpperCase())
// 'Hello Big World'

The arguments are the whole match, then each capture group, then the offset, then the whole input, and, when the pattern has named groups, the groups object as the last argument:

'a1 b22'.replace(/([a-z])(\d+)/g,
  (match, letter, digits, offset, whole) => `${letter.toUpperCase()}${digits * 2}@${offset}`)
// 'A2@0 B44@3'

The number of arguments varies with the number of groups, which is why code that uses named groups reads the last argument, args.at(-1). A group that didn’t participate is undefined in a function but expands to an empty string in a template. For the input 'a' and the pattern /(a)(b)?/, the function version printed [a|undefined] and the '[$1|$2]' version printed [a|].

Don’t put user text in the template

Because the replacement string is parsed, text with a $ in it changes meaning:

const user = "cost $& more";
'X'.replace(/X/, user)          // 'cost X more'
'X'.replace(/X/, () => user)    // 'cost $& more'

The first line expanded $& to the match, X. The function form returns the string untouched. Whenever the replacement comes from outside your program, use the function form.

Python’s re.sub

Python’s version is re.sub(pattern, repl, string, count=0). The replacement can be a template with backslash references, or a function that receives the match object:

re.sub(r'(\w+) (\w+)', r'\2 \1', s)               -> 'Lovelace Ada, Hopper Grace'
re.sub(r'(\w+) (\w+)', r'\2 \1', s, count=1)      -> 'Lovelace Ada, Grace Hopper'
re.sub(r'(?P<f>\w+) (?P<l>\w+)', r'\g<l> \g<f>', s) -> 'Lovelace Ada, Hopper Grace'
re.sub(r'(\w)(\w*)', lambda m: m.group(1).upper() + m.group(2), 'hello big world')
                                                  -> 'Hello Big World'
re.subn(r'\d+', '#', 'a1 b22 c333')               -> ('a# b# c#', 3)

subn also returns the number of replacements. Use \g<2> when the next character is a digit: r'\g<2>0 \1' gave Lovelace0 Ada,, unambiguous. Python is stricter than JavaScript about mistakes. An unknown escape, re.sub('a', r'\d', 'a'), raised re.error: bad escape \d, and a missing group, r'\2' with one group, raised re.error: invalid group reference 2. JavaScript quietly leaves $2 as text. Python has no $ tokens at all: re.sub(r'(a)', '[$&]', 'a') returned the literal [$&]. An unmatched group is None in a function, as in [a|None], but an empty string in a template, as in [a|]. And a function returns text untouched: lambda m: r'cost \1 more' inserted cost \1 more.

Empty matches and sed

A pattern that can match nothing replaces at every position: 'abc'.replace(/x*/g, '-') gave -a-b-c-, and Python 3.9 agreed. On the command line, sed has the same idea: echo 'Ada Lovelace' | sed -E 's/([A-Za-z]+) ([A-Za-z]+)/\2, \1/' printed Lovelace, Ada, & is the whole match (s/a/[&]/ turned cat into c[a]t), and Perl’s s/(\w+) (\w+)/$2, $1/ on the same input matched JavaScript’s tokens. The sed lesson covers its flags.

About the video

The embedded video is The Coding Train’s “2.9: Regular Expressions: replace() - Programming with Text”, published 19 September 2016 and 18 minutes 49 seconds long. Its chapters include replace function basics, simple text replacement, using regular expressions, capturing groups, callback functions and advanced group handling. The description says the replacement can be a literal string or a callback that builds the string with logic. It uses JavaScript, so Python’s re.sub, the $ tokens other than group references, and the user-text trap above are not in it as far as I can tell. I couldn’t read a transcript. English per its title and description.

What I did not run

GNU sed’s extensions, a replaceAll with a regex that has the y flag, and editor replace boxes (the last lesson in this group).

Next

Replacing keeps the text between matches. Splitting and extracting uses the matches as delimiters, or collects them as the result.

Check yourself

  1. 01How do you turn 'Ada Lovelace' into 'Lovelace, Ada' in JavaScript and in Python?

    JavaScript: 'Ada Lovelace'.replace(/(\w+) (\w+)/, '$2, $1'). Python: re.sub(r'(\w+) (\w+)', r'\2, \1', text). Same pattern, different token for the group references.

  2. 02What does 'a'.replace(/(a)/, '$10') return when the pattern has only one group?

    a0. There is no group 10, so the engine reads $1 followed by the character 0. Use a named group or restructure if you ever need a digit right after a group reference.

  3. 03Why would you use a replacer function to insert a user-supplied string?

    A replacement string treats $&, $1 and $$ as tokens, so a user's text like 'cost $& more' comes out as 'cost X more'. Returning the text from a function, () => user, inserts it verbatim.

  4. 04What does a group that did not participate look like to a JavaScript replacer function, versus a $2 token?

    To the function it is undefined, so a template string prints the word undefined. In a replacement string, $2 for an unmatched group expands to an empty string.

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