Regex Cheatsheet

1 minute read

Published:

This guide details the quintessential parts of regular expressions (at least for me). A more detailed list of operators can be found here.

// in the following example, the `/` is used to wrap the regex. `\d+` represents numbers from 0 to 9. // the `g` tag indicates global search
var r = /\d+/g 

Regex Basics

The following characters indicate some category of characters. Using these symbols alone will represent one character that matches its parameter. Note that capitalizing the symbol will indicate the opposite of its parameter.

SymbolMeaning
\dAny one digit (0 to 9) *Python: unicode digit in any script
\wASCII letter, digit or underscore *Python: unicode letter, ideogram, digit or underscore
\sWhitespace characters (tab, newline, space etc.) *Python/JS: unicode separator
\DOpposite of \d (NOT a digit)
\WOpposite of \w (NOT a word character)
\SOpposite of \s (NOT a whitespace)

Logic Operators

These logic operators allow you to chain multiple search parameters

SymbolMeaningExample
|Alternation OR operanda|b
( … )Group 
\xContents of group x (x is an int)’(\d\d) + (\d\d) = \2 + \1’ > ‘3 + 4 = 4 + 3’
(?: … )Exclude group 

Quantifiers

These indicate number of times to search for the pattern.

SymbolMeaning
+Greedy search (one or more)
{x}Exactly x times
{x, y}x to y number of times
{x,}x or more times
*Zero or more times
?Once or none

Lookaround Characters

These are sort of like conditional operators. This post explains it in more detail. In all honesty I rarely use these, but they are cool to know.

SymbolMeaningExample
(?=…)Positive lookaheadAsserts that ... comes after the current position
(?<=…)Positive lookbehindAsserts that ... comes before current position
(?!…)Negative lookaheadAsserts that ... is definitely not after current position
(?<!…)Negative lookbehindAsserts that ... is definitely not before current position