Learn regular expressions · Lesson 2

Special characters and escaping

These are the common metacharacters in Perl-style regular expressions, the kind most languages use, outside brackets:

. * + ? ( ) [ ] { } | ^ $ \

The lessons to come explain each. For now: to match one of them as itself, put a backslash before it. \. is a plain dot, \$ a dollar sign, \\ a backslash. Some engines let a lone ] or } pass as a plain character, but not all (JavaScript with the u or v flag refuses them), so escape those too: \], \}.

A dot is not a dot

The most common mistake is the dot. Unescaped it matches any character, so a pattern for a price can match more than you meant:

/3.50/g3 matches
3.50 and 3,50 and 3550
Try it in Dotstar →

Escaped, it matches only a dot:

/3\.50/g1 match
3.50 and 3,50 and 3550
Try it in Dotstar →

The same goes for a file name: report.pdf also matches report-pdf. (And \.pdf$ is what you mean by “ends in .pdf”: $ is the end of the text, as the lesson on anchors explains.)

Escaping too much

A backslash before a letter or digit usually doesn’t make it plain: it makes it special. \d is a digit, \b the edge of a word, \1 the text a group matched; later lessons come to each. So escape the punctuation above, and leave letters alone. Escaping other punctuation, like \# or \@, is harmless in most flavors, but not in all: JavaScript with the u or v flag refuses escapes it doesn’t know.

A slash in JavaScript

In JavaScript a pattern is often written between slashes, /cat/g, as in these lessons. The slash isn’t regex syntax, but inside /…/ it ends the pattern, so a slash in it is written \/: /\d+\/\d+/ for 3/4. Patterns given as strings, in JavaScript’s new RegExp("…") and in most other languages, need no escaping for it.

The string around the pattern

In code the pattern is usually inside a string, and strings have backslashes of their own. In Java, C# (without @), Go (without backticks) and C++ (without R"(…)"), \d has to be written "\\d", and a plain backslash "\\\\". Python’s raw strings, r"\d", and JavaScript’s /\d/ avoid that. Dotstar’s Code tab does the escaping for you.

/(ab)+/gin each engine
abab (ab)+
JavaScript, PCRE2, Python, POSIX EREabab ab
POSIX BRE(ab)+

Run in each engine itself, as Dotstar’s Compare runs them, when this page was checked.