Guides / Regex Cheatsheet

Regex Cheatsheet for Developers

6 min read · Regular Expressions

What is a regular expression?

A regular expression (regex) is a sequence of characters that defines a search pattern. Regex is used to find, match, extract, or replace text based on patterns rather than exact strings. It is supported natively in JavaScript, Python, Java, Go, Ruby, PHP, and most other languages.

Example: the pattern \d+matches any sequence of one or more digits — it would match "42", "100", and "9" in a string.

Anchors

PatternDescription
^Start of string (or line in multiline mode)
$End of string (or line in multiline mode)
\bWord boundary
\BNot a word boundary

Character classes

PatternDescription
.Any character except newline
\dDigit [0-9]
\DNot a digit
\wWord character [a-zA-Z0-9_]
\WNot a word character
\sWhitespace (space, tab, newline)
\SNot whitespace
[abc]Any of a, b, or c
[^abc]Any character except a, b, c
[a-z]Any lowercase letter
[A-Z]Any uppercase letter

Quantifiers

PatternDescription
*Zero or more
+One or more
?Zero or one (optional)
{n}Exactly n times
{n,}n or more times
{n,m}Between n and m times
*?Zero or more (lazy / non-greedy)
+?One or more (lazy / non-greedy)

Groups and references

PatternDescription
(abc)Capture group — captures "abc"
(?:abc)Non-capturing group
(?<name>abc)Named capture group
\1Backreference to group 1
a|bAlternation — a or b

Lookahead & lookbehind

PatternDescription
(?=abc)Positive lookahead — followed by abc
(?!abc)Negative lookahead — not followed by abc
(?<=abc)Positive lookbehind — preceded by abc
(?<!abc)Negative lookbehind — not preceded by abc

Flags

PatternDescription
gGlobal — find all matches, not just first
iCase-insensitive
mMultiline — ^ and $ match start/end of each line
sDotall — . matches newlines too
uUnicode — enables Unicode support

Common patterns

Email address
^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$
URL
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b
IPv4 address
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$
Date (YYYY-MM-DD)
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
Hex color
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
Phone number (US)
^\+?1?\s*\(?\d{3}\)?[\s.\-]?\d{3}[\s.\-]?\d{4}$
Slug (URL-safe)
^[a-z0-9]+(?:-[a-z0-9]+)*$
Strong password
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

Tips for writing regex

  • Start simple — match the common case first, then handle edge cases
  • Use non-capturing groups (?:...) when you do not need to reference the group later
  • Prefer specific character classes over . to avoid unintended matches
  • Use anchors ^ and $ to match full strings, not substrings
  • Test your regex against both valid and invalid inputs
  • Add comments when the pattern is complex — some languages support verbose mode

Test your regex live

Write a pattern, add test strings, and see matches highlighted in real time.

Regex Tester →