Regular Expressions Cheat Sheet - CodeSwordsman

Regex syntax reference: character classes and quantifiers, anchors and groups, lookarounds and flags, plus ready-to-use patterns for email, URL, IPv4 and dates, with grep -P and sed -E differences.

PCRE / JavaScript RegExpUpdated 2026-10-3025 commands

Characters & Quantifiers

Dot matches any char except newline; \d digit, \w word char, \s whitespace

.\d\w\s

Uppercase forms negate: non-digit, non-word, non-whitespace

\D\W\S

Zero or more, one or more, and zero or one

* + ?

Bounded repetition: {3} exactly three, {3,} at least three

\d{3,5}

Appending ? makes it lazy, stopping at the nearest closing token

<.+?>

Character classes select one option; ^ inside brackets negates

[abc] [a-z0-9_] [^0-9]

Anchors & Groups

^ anchors the start and $ the end; use the m flag for multiline text

^start
end$

Word boundary prevents matching word inside sword

\bword\b

Parentheses capture groups referenced as $1 and $2 in replacements

(\d{4})-(\d{2})

Non-capturing group clusters alternatives without numbering

(?:https?|ftp)://

A backreference requires the same text again, handy for duplicate words

^(\w+)\s+\1$

Lookaround

Positive lookahead matches digits followed by a unit without consuming it

\d+(?=元)

Positive lookbehind matches digits preceded by a currency symbol

(?<=¥)\d+

Negative lookahead excludes matches followed by a specific unit

\d+(?!px)

Flags

Global match returns all results instead of the first one

/pattern/g

Case-insensitive matching instead of writing [a-zA-Z]

/pattern/i

m makes ^ and $ per line, s lets the dot match newlines

/^line$/m
/.*/s

The u flag enables Unicode property escapes such as Han script

/\p{Script=Han}/u

Common Patterns

Basic email validation; still verify by sending a confirmation mail

^[\w.+-]+@[\w-]+\.[\w.]+$

Permissive URL check that blocks obviously invalid input

^https?://[^\s/]+(/[^\s]*)?$

IPv4 validation constraining each octet to 0-255

^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$

YYYY-MM-DD format check without month-length validation

^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$

Command-Line Differences

-P enables PCRE for \d and lookarounds; BSD/macOS grep lacks it

grep -P "\d{3}-\d{4}" file.txt

-E enables extended regex so | and + need no escaping

grep -E "^(ERROR|WARN)" app.log
sed -E "s/ +/ /g" file.txt

Escape metacharacters when replacing; double backslashes in RegExp strings

echo "a.b*c" | sed "s/[.*]/\&/g"

This website uses cookies to ensure you get the best experience on our website. Privacy Policy.