Regular Expressions for Beginners: 12 Patterns You'll Actually Use
Learn regex syntax step by step with practical patterns for emails, phone numbers, dates, URLs and more, plus tips to avoid catastrophic backtracking.
Last updated · 2026-09-12
The building blocks
A regular expression is a pattern describing text. Literal characters match themselves; special characters add meaning. \d matches a digit, \w a word character, \s whitespace and . any character. Quantifiers say how many: * zero or more, + one or more, ? optional and {2,4} between two and four. ^ and $ anchor the start and end.
Open our regex tester in another tab and try each pattern below as you read.
Validation patterns
Simple email: ^[^\s@]+@[^\s@]+\.[^\s@]+$ — good enough for forms; confirm with a verification email.
ISO date: ^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$.
Hex color: ^#(?:[0-9a-fA-F]{3}){1,2}$.
US ZIP code: ^\d{5}(-\d{4})?$.
Strong password rule (8+ chars, letter and digit): ^(?=.*[A-Za-z])(?=.*\d).{8,}$.
Slug: ^[a-z0-9]+(?:-[a-z0-9]+)*$.
Extraction patterns
URLs in text: https?:\/\/[^\s]+ with the g flag.
Hashtags: #[\p{L}\d_]+ with the u flag for international letters.
Numbers including decimals: -?\d+(\.\d+)?.
Text between quotes: "([^"]*)" — the group captures the content.
Search and replace
Collapse whitespace: replace \s+ with a single space. Reformat dates from 2026-10-09 to 09/10/2026 with (\d{4})-(\d{2})-(\d{2}) and the replacement $3/$2/$1.
"2026-10-09".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1"); // "09/10/2026"Greedy vs lazy
Quantifiers are greedy: <.+> on '<a><b>' matches the whole string. Add ? to make them lazy: <.+?> matches '<a>' then '<b>'. This is the source of most 'my regex matches too much' bugs.
Avoid catastrophic backtracking
Nested quantifiers such as (a+)+ or (\w*)* can take exponential time on inputs that almost match, freezing a server — an attack known as ReDoS. Keep patterns specific, avoid nesting quantifiers over the same characters and limit input length before matching user data.