Regex Cheat Sheet: Common Patterns & Examples
What Are Regular Expressions?
Regular expressions (regex) are patterns used to match character combinations in strings. They are supported in virtually every programming language and are essential for tasks like validation, search-and-replace, and data extraction.
Learning regex can feel daunting at first, but once you understand the building blocks, you can construct powerful patterns quickly. This cheat sheet covers the syntax you will use most often.
Basic Syntax Reference
Character Classes
.— any character except newline\d— any digit (0–9)\D— any non-digit\w— any word character (letter, digit, underscore)\W— any non-word character\s— any whitespace (space, tab, newline)\S— any non-whitespace[abc]— any of a, b, or c[^abc]— anything except a, b, or c[a-z]— any lowercase letter
Quantifiers
*— 0 or more+— 1 or more?— 0 or 1 (optional){3}— exactly 3{2,5}— between 2 and 5{2,}— 2 or more
Anchors
^— start of string (or line in multiline mode)$— end of string (or line in multiline mode)\b— word boundary
Groups & Alternation
(abc)— capture group(?:abc)— non-capturing groupa|b— alternation (a or b)(?=abc)— positive lookahead(?!abc)— negative lookahead
Common Real-World Patterns
Email Address
^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$
Matches most standard email addresses. For production validation, use a dedicated library or send a confirmation email.
URL
https?:\/\/[\w.-]+(?:\.[a-zA-Z]{2,})[\/\w.-]*\/?
Phone Number (US)
^\+?1?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$
IP Address (IPv4)
^(?:\d{1,3}\.){3}\d{1,3}$
Date (YYYY-MM-DD)
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
Strong Password
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Requires at least one lowercase, one uppercase, one digit, one special character, and a minimum of 8 characters.
Hex Color Code
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
Try It Now
Use our free Regex Tester to build and test patterns with live highlighting and match details.
Regex Tester →Tips for Writing Better Regex
- Start simple. Build your pattern incrementally and test after each addition.
- Use non-greedy quantifiers (
*?,+?) when you want the shortest possible match. - Anchor your patterns with
^and$when validating entire strings. - Use named groups (
(?<name>...)) for readability in complex patterns. - Comment your regex using the verbose flag (
x) in Python or separate documentation.
Conclusion
Regular expressions are a powerful tool that every developer should have in their toolkit. Bookmark this cheat sheet for quick reference, and use our Regex Tester to experiment with patterns in real time.