Literals and escaping

Beginner · 7 min

Most characters in a pattern match themselves; a few do not. Learn the metacharacters, why . needs \. , and how string literals double the backslashes.

Before thisWhat a regular expression is

Wendi Jollymore · 27 min · from 1:14

Literals and escaping

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

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

What you'll learn

  • A literal is a character that matches itself. A pattern made only of literals is plain substring search, and it is case-sensitive.
  • In JavaScript the metacharacters are ^ $ \ . * + ? ( ) [ ] { } |. A backslash in front of one makes it literal, so \. matches a real dot.
  • An unescaped . matches any character, so /3.14/ also matches 3x14. This is the most common regex bug.
  • A string literal eats backslashes before the regex engine sees them: new RegExp("3\\.14") works, new RegExp("3\.14") silently means 3.14 with a wildcard dot. String.raw or a regex literal avoids the problem.
  • Escaping rules are per flavour. In grep's basic syntax + is a plain character and \+ is the operator. In grep -E it is the other way round.

The simplest pattern

Start with a pattern that contains only ordinary letters. In /cat/ each character matches itself, one after the other, so the pattern means “the letters c, a, t in that order”. That is the same as substring search:

"concatenate".match(/cat/)   // [ 'cat', index: 3, ... ]
"Cat".match(/cat/)           // null

It found cat inside concatenate, because nothing in the pattern says anything about word edges. It did not find Cat, because matching is case-sensitive unless you ask otherwise. A character that stands for itself is called a literal.

If every character were a literal, a regex could never express “any digit” or “one or more”. So some characters are reserved to mean something else. These are the metacharacters.

The characters that are not literal

In JavaScript the set is ^ $ \ . * + ? ( ) [ ] { } |. Of those, \ * + ? ( ) [ cannot stand alone as a pattern. I tried each one by itself with new RegExp(char):

"^"->^   "$"->$   "\\"->SyntaxError   "."->.   "*"->SyntaxError   "+"->SyntaxError
"?"->SyntaxError  "("->SyntaxError   ")"->SyntaxError   "["->SyntaxError
"]"->]   "{"->{   "}"->}   "|"->|

^, $, . and | are valid alone because they have meaning with nothing around them. ], { and } are accepted alone only because JavaScript’s default mode is forgiving. Add the u flag and /{/u fails with “Lone quantifier brackets”. Don’t rely on the forgiveness. Escape all of them.

Two more characters matter in specific places. The slash ends a regex literal, so /a\/b/ needs the backslash (and String(new RegExp("/")) printed /\//). The dash is special only inside square brackets, which the character classes lesson covers.

The dot bug

The dot is the one that bites. . means “any one character except a line break”, so an unescaped dot matches far more than a dot:

const s = "version 3.14 and 3x14, price $5 (approx)";
s.match(/3.14/g)     // [ '3.14', '3x14' ]
s.match(/3\.14/g)    // [ '3.14' ]

A backslash before a metacharacter escapes it: the engine drops its special meaning and matches it as a literal. The same goes for the other reserved characters:

/\$5/.test(s)        // true
/$5/.test(s)         // false  ($ is an end-of-text anchor here)
s.match(/\(approx\)/)[0]   // (approx)
new RegExp("(approx")      // SyntaxError: Invalid regular expression: /(approx/: Unterminated group

Inside a character class most metacharacters are already literal, so /[.]/.test("a") is false and /[.]/.test(".") is true.

Escaping twice

A pattern often lives inside a string, such as the argument to new RegExp(...) or a Python call. The string literal is parsed first, and it has escape rules of its own. In JavaScript a backslash before a character it doesn’t know is dropped:

"\\.".length   // 2  -> the characters \ and .
"\.".length    // 1  -> just a dot
new RegExp("3\\.14").test("3x14")   // false  (correct)
new RegExp("3\.14").test("3x14")    // true   (the escape vanished)

The fix is to double every backslash, or to skip string escaping altogether. String.raw leaves backslashes alone: new RegExp(String.raw3.14).test("3x14") is false. A regex literal like /3\.14/ has no string layer at all.

Python has the same trap and the standard cure, raw strings. In Python 3.9, "3\.14" happens to work, because an unknown escape keeps its backslash, but it is a latent bug. Running it with python3 -W error turned it into SyntaxError: invalid escape sequence \.. Write r"3\.14".

If the text to match comes from a variable, use the language’s escape helper. Python has re.escape("a.b*c(d)"), which printed a\.b\*c\(d\). Node 26 has RegExp.escape, which printed \x33\.14\x20\(approx\) for "3.14 (approx)". It also hex-escapes a leading digit and a space, which is ugly but still matches the same text. The later lesson on building patterns from input goes further.

The escape rules change by tool

Which characters are special depends on the flavour. In grep’s default basic syntax, + is an ordinary character:

$ printf 'a+b\naab\n' | /usr/bin/grep 'a+b'
a+b
$ printf 'a+b\naab\n' | /usr/bin/grep -E 'a+b'
aab
$ echo aab | /usr/bin/grep -oE 'a\+b'; echo "exit $?"
exit 1

With -E the roles flip: a+b means “one or more a, then b”, and a\+b looks for a literal plus (and found nothing in aab). The same holds for parentheses: echo x | grep '(x)' printed nothing and grep -E '(x)' printed x. BSD grep also accepted a\+b in basic mode, as GNU does, but that is an extension to POSIX, so don’t rely on it. Flavors and the common core lays this out in full.

About the video

Wendi Jollymore’s “Basic Regular Expressions 4 - Meta-Characters & OR Operator” was published on 18 April 2022 and runs 27 minutes 11 seconds. Its description lists key moments: “Need for Escaping” at 1:14, “Escape Example” at 3:41 and “Example” at 5:39, then meta-characters for digits and words at 8:41. The embed plays only from 1:14 to 8:41, the escaping part. The description names regexr as the tester. I couldn’t read a transcript, so I don’t know which flavour’s rules she uses, and the lesson’s string-literal double escaping may not appear in the video at all. English per its title and description.

What I did not run

GNU grep, regex101 and regexr. I only ran the JavaScript, Python 3.9 and BSD grep examples shown above.

Next

You can now write patterns that match fixed text, including text full of punctuation. Testing patterns in regex101 and the console sets up the loop you’ll use for the rest of the roadmap.

Check yourself

  1. 01Why does /3.14/ match the string '3x14'?

    The unescaped dot is a metacharacter that matches any single character, and x is a character. Write /3\.14/ to require a real dot.

  2. 02What does new RegExp("3\.14") match, and why?

    It matches 3x14 as well as 3.14. The JavaScript string literal turns \. into a plain dot before RegExp sees it, so the pattern is 3.14 with a wildcard. The string needs "3\\.14".

  3. 03How do you match the literal text (approx) in JavaScript?

    Escape both parentheses: /\(approx\)/. Without the backslashes the parentheses form a group, and an unbalanced one is a SyntaxError.

  4. 04Does + mean 'one or more' in every tool?

    No. In grep's basic syntax a bare + is a literal plus sign and \+ is the operator, while in grep -E and in JavaScript a bare + is the operator and \+ is the literal.

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