Regular Expressions Cheat Sheet
A regular expression is a pattern that matches text: for validating input, extracting parts of a string, searching, or find-and-replace. The core syntax is shared by most languages, but flavours differ in details (lookbehind support, named-group syntax, Unicode classes), so check the language's documentation for anything beyond the basics.
Overview
| Symbol | Meaning | Example |
|---|---|---|
. |
any character except newline | a.c matches abc |
^ / $ |
start / end of the string (or line in multiline mode) | ^users/$ |
[abc] |
one character from the set | [0-9], [a-z] |
[^abc] |
one character not in the set | [^-\w ] |
\d \w \s |
digit, word character (letters, digits, _), whitespace |
\w+ |
* + ? |
0 or more, 1 or more, 0 or 1 | colou?r |
{n} {n,m} |
exactly n, between n and m | [0-9]{4} |
( ) |
capturing group | ([0-9]+) |
(?P<name>...) |
named group (Python) | (?P<user_id>[0-9]{4}) |
| |
alternative | cat|dog |
\ |
escape a special character | \. matches a dot |
Write patterns as raw strings in Python (r"\d+") so backslashes reach the regex engine untouched.
Details
Python
import re
re.fullmatch(r"[0-9]{4}", "2024") # whole string must match
m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})", "Due 2024-09-30")
m.group("year") # "2024"
re.sub(r"\s+", " ", "too many spaces") # "too many spaces"
Ruby: Remove Unwanted Characters
term = term.gsub(/[^-\w ]/, "")
Keeps hyphens, word characters and spaces, removes everything else. gsub returns a new string; gsub! changes it in place. Useful to normalise a search term. It is not an injection defence: use parameterised queries for that.
Django: re_path
from django.urls import path, re_path
urlpatterns = [
re_path(r"^dashboard/users/(?P<user_id>[0-9]{4})/$", views.user_detail),
]
A named group is passed to the view as a keyword argument (user_id, a string); an unnamed group is passed positionally. path() with a converter covers most cases more readably; use re_path() when the format needs a pattern, such as exactly four digits.
References
- Python documentation: re - syntax and functions.
- Ruby documentation: Regexp - Ruby's flavour.
- Django documentation: re_path() - regular expressions in URL patterns.
- Programming Languages MOC - hub for language notes.
Review cards
Flashcard Why write Python regex patterns as raw strings?
So that Python doesn't process the backslashes first. In a normal string '\b' is a backspace character; in r'\b' it reaches the regex engine as a word boundary.
Flashcard What does the `re.fullmatch` function in Python do?
It checks if the entire string matches the pattern.
Flashcard What does term.gsub(/[^-\w ]/, "") keep, and is it an injection defence?
It keeps hyphens, word characters and spaces and removes everything else. It normalises a search term; it is not an injection defence, which takes parameterised queries.