Regular expressions (regex) are powerful patterns used to match, search, and manipulate text. Every developer encounters regex at some point — whether validating user input, parsing logs, or doing search-and-replace operations across codebases.
Basic Syntax
Character Classes
. — matches any character except newline\d — matches any digit (0-9)\D — matches any non-digit\w — matches any word character (letters, digits, underscore)\W — matches any non-word character\s — matches any whitespace (space, tab, newline)\S — matches any non-whitespace characterQuantifiers
* — zero or more times+ — one or more times? — zero or one time{n} — exactly n times{n,} — n or more times{n,m} — between n and m timesAnchors
^ — start of string (or start of line with multiline flag)$ — end of string (or end of line with multiline flag)\b — word boundaryCommon Flags
g — global: match all occurrencesi — case-insensitive matchingm — multiline: ^ and $ match line boundariess — dotall: . matches newline charactersu — unicode supportGrouping and Alternation
(abc) — capturing group(?:abc) — non-capturing groupa|b — alternation (a or b)Lookaheads and Lookbehinds
(?=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)Common Real-World Patterns
Email Validation
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
URL Validation
^https?:\/\/(www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\/.*)?$
Phone Number (US)
^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
IPv4 Address
^(\d{1,3}\.){3}\d{1,3}$
Hex Color
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
Password Strength (min 8 chars, 1 upper, 1 lower, 1 digit)
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$
Tips for Writing Regex
(?:) when you don't need the matched text.*Try our Regex Tester to test and debug your regular expressions in real time.
