Regular expressions can look like a secret code, but they are incredibly powerful for searching, extracting, and replacing text. This quick reference sheet breaks down the essential building blocks so you can start writing effective patterns immediately.
Character classes act as shortcuts for common types of data, allowing you to match specific types of characters without listing them all out manually.
| Syntax | Matches | Example Match |
|---|---|---|
. | Any single character (except a newline) | a.c matches abc, a1c |
\d | Any digit (0-9) | \d\d matches 42, 07 |
\D | Any non-digit character | \D matches A, @, space |
\w | Any word character (a-z, A-Z, 0-9, _) | \w+ matches Hello_World |
\s | Any whitespace (space, tab, newline) | \w\s\w matches a b |
[abc] | Any single character in the brackets | [A-Z] matches B, X |
[^abc] | Any single character not in the brackets | [^0-9] matches any non-number |
Quantifiers tell the regex engine how many times a pattern should occur. Boundaries anchor your search to specific parts of the text.
| Syntax | Description | Example Match |
|---|---|---|
* | Zero or more occurrences | ab*c matches ac, abc, abbbc |
+ | One or more occurrences | ab+c matches abc, abbc |
? | Zero or one occurrence (optional) | colou?r matches color, colour |
{n,m} | Between n and m occurrences | \d{2,4} matches 12, 123, 1234 |
^ | The start of a string/line | ^Hello matches Hello at the beginning |
$ | The end of a string/line | end$ matches end at the tail |
| | Alternation (OR logical operator) | cat|dog matches cat or dog |
\) first (e.g., \. matches a literal period).* and + are "greedy" and match as much text as possible. Append a ? (e.g., *? or +?) to make them "lazy" so they stop at the earliest possible match.r (e.g., r"\d+") so the compiler doesn't accidentally misinterpret your backslashes.