Find and replace in editors, and patterns from user input

Intermediate · 2 min

Reuse capture groups in an editor's replace box, then build a regex from user text safely with RegExp.escape, and see why raw input is injection.

Before thisReplacing with regexMatching in JavaScriptRegex on the command line

Code 2020 · 2 min

Find and replace in editors, and patterns from user input

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

Taught by Code 2020Report a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A regex-mode replace box works like replace in code: a capture group in the find box can be reused in the replace box. The video's description says VS Code uses $1, $2 and so on, with $0 for the whole match.
  • Editors differ in what token they use for a group, so check the token for your editor before a bulk replace, and preview the matches before you press replace-all.
  • Text typed by a user is text, not a pattern. new RegExp(userInput) treats . as any character, throws on ( or +, and can match everything with .*. Escape it first.
  • Node 26 has RegExp.escape(). A hand-rolled escapeRegExp, s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), covers the usual metacharacters but leaves - alone, which matters inside a character class.
  • Escaping makes the text literal, not the pattern safe in other ways. A user-supplied pattern can still be exponentially slow, and \b around escaped text fails when the text begins or ends with a symbol, like C++.

Two places where a pattern meets a person

This lesson joins two situations that look different. In one, you are the person: you type a regex into an editor’s find box. In the other, someone else is: they type text into your program, and you build a regex from it. In both, the question is what counts as pattern and what counts as plain text.

I should be plain about the split. The video is a short VS Code tip that covers the first half. The second half is from my own runs.

Capture groups in an editor’s replace box

In code you wrote '$2, $1' to reorder groups. Editors with a regex mode work the same way. You turn on the regex toggle, put groups in the find box, and use them in the replace box. The video’s description says VS Code takes $1, $2 and so on for the groups and $0 for the whole match, and that the feature is handy for transforming text. I didn’t run VS Code, so that is its description, not my test.

Here is the same idea on a list. With find (\w+), (\w+) and replace $2 $1, the line Lovelace, Ada becomes Ada Lovelace. I ran the equivalent in JavaScript, where a replacement string with the same $1 tokens is standard:

'Lovelace, Ada'.replace(/(\w+), (\w+)/, '$2 $1')   // 'Ada Lovelace'

Be aware that editors don’t agree on the token. JavaScript and VS Code (per the video) use $1. sed uses \1, as I showed in the replacing lesson. Don’t assume. A few habits help with bulk edits: look at the match count before replacing, step through the first few matches, and prefer a pattern anchored well enough that it can’t match unrelated lines.

Building a pattern from input

Now the other direction. A search box filters a list. The user types a.c, and your code does new RegExp(input). I tried six inputs against the list ['a.c', 'abc', 'a+c', 'Total (USD)']:

input    raw regex gives                          escaped gives
"a.c"    ["a.c","abc","a+c"]                      ["a.c"]
"a+c"    []                                       ["a+c"]
"(USD)"  ["Total (USD)"]                          ["Total (USD)"]
".*"     everything                               []
"C++"    SyntaxError: Nothing to repeat           []
"["      SyntaxError: Unterminated character class  []

Typed raw, a.c matched abc because the dot is a wildcard, a+c found nothing because + means “one or more a”, .* matched every line, and two inputs threw a SyntaxError. Each of these is a small instance of regex injection: input that should have been data became part of the program. Think of SQL injection with a smaller blast radius. The fix is to escape the input, putting a backslash in front of every metacharacter so it matches itself.

Two ways to escape

The hand-rolled version, which is widely copied, is:

const escapeRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
escapeRegExp('a.b*c(d)[e]{f}|g^h$i\\j+k?l')
// a\.b\*c\(d\)\[e\]\{f\}\|g\^h\$i\\j\+k\?l

The replacement '\\$&' is a backslash followed by the whole match. It turned each metacharacter into an escaped one, and a pattern built from the result matched the original text. Node 26 also has a built-in, RegExp.escape. It gave the same on the symbols, with an unfamiliar first character:

RegExp.escape('a.b*c')        \x61\.b\*c
RegExp.escape('1+1')          \x31\+1
RegExp.escape('hello world')  \x68ello\x20world
RegExp.escape('x-y,z')        \x78\x2dy\x2cz

It hex-escapes a leading letter or digit and some punctuation such as the space, hyphen and comma, so the result is safe in more places. The difference showed up inside a character class. new RegExp('^[' + escapeRegExp('a-c') + ']+$') matched b, because the unescaped hyphen made a-c a range. With RegExp.escape('a-c'), which gave \x61\x2dc, b didn’t match and a-c did. Prefer the built-in where it exists. I only checked Node 26, so before relying on RegExp.escape in a browser or older Node, check support, and keep a fallback.

Python has re.escape. On 3.9 re.escape('C++') returned C\+\+, and it escaped the space and hyphen in my longer test too. The Python lesson covers the rest of the module.

If you only need literal text, skip the regex

For a literal search, plain string functions need no escaping: 'a.b.c'.replaceAll('.', '-') gave a-b-c, 'a.b.c'.split('.') gave ['a', 'b', 'c'], and includes('.') was true. Use regex only when you need what it adds, such as case-insensitivity, word edges or several alternatives.

Escaping does not solve everything

Two traps remain after escaping.

Word boundaries. Wrapping escaped input in \b fails when the text begins or ends with a symbol. On I like C++ and C# and C, \bC\+\+\b returned null, because there is no word edge between + and a space. The lookaround form (?<!\w) before and (?!\w) after found C++ and C#. Which one you want is a design choice, since both treat the C in C++ as a match for C.

Speed. Escaping is for text you want taken literally. If you do mean to run a user’s own pattern, a short one can be very slow. I timed /^(a+)+$/ on a string of as followed by !, and the time roughly doubled per extra character:

n=24  71 ms     n=26  310 ms     n=28  1213 ms     n=30  4793 ms

That is the shape the how-engines-work lessons explain. For now, the lesson is that accepting a pattern from outside means limiting its length, or using an engine that guarantees linear time, or both.

About the video

The embedded video is “VS Code tips — Using regex capture groups in find replace” from the channel “Code 2020”, published 2 April 2020 and 1 minute 50 seconds long. The description says that when using regular expressions in find and replace, you can reference capture groups in the replacement with $1, $2 and so on, and $0 for the entire match. It has no chapters, and I couldn’t read a transcript. It covers only the editor half of this lesson, and only for VS Code. The building-patterns-from-input half has no embedded video: Learn with Shikaar’s three-minute “Escape Special Characters for RegEx in JavaScript the Right Way!”, linked under “deeper”, is the closest one I found, and I judged it a weaker pick for the embed. English per its title and description.

What I did not run

VS Code itself, any other editor’s replace box, RegExp.escape in browsers, a linear-time engine such as RE2, and the video’s examples.

Next

That finishes the group on using regex in programs. The next group, starting with Unicode code points and the u flag, looks at what the engine counts as a character.

Check yourself

  1. 01In an editor's regex replace box, how would you turn 'Lovelace, Ada' into 'Ada Lovelace'?

    Find (\w+), (\w+) and replace with $2 $1, if your editor uses the dollar form that VS Code does. The two groups capture the surname and given name, and the replacement puts them in the other order.

  2. 02Why does searching a list for the user's text '.*' with new RegExp(input) match everything?

    . * means zero or more of any character, so it matches every line. The input was typed as plain text but interpreted as a pattern. Escaping it first made it match only a literal dot followed by a star.

  3. 03What does escapeRegExp('a-c') leave unchanged that RegExp.escape escapes, and when does it matter?

    The hyphen. Inside a character class, an unescaped hyphen makes a range, so [a-c] matches b, while the escaped one, [\x61\x2dc], matches only a, the hyphen and c. Insert escaped text inside brackets only with a function that escapes the hyphen.

  4. 04Why is escaping not the end of the problem when a user can type a pattern?

    Escaping works when you want the text as a literal. If you intend to run the user's actual regex, escaping defeats the purpose and not escaping lets them write patterns like (a+)+$ that took 4.8 seconds on 30 characters in my test. Limit the input length, or run it with a linear-time engine.

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