Regular expressions—commonly called regex—look intimidating at first glance. A pattern like ^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$ appears cryptic, but it is simply a precise, compact set of rules for describing text. Once you understand the building blocks, you can write patterns like this yourself in minutes.
This guide explains regex from the ground up. By the end, you will understand every symbol, be able to read patterns you encounter in code, and write your own patterns to validate emails, extract phone numbers, clean messy data, and more.
The Quick Answer: What Does a Regex Pattern Mean?
Here is how to read a common regex pattern at a glance:
^(\d{3})-(\d{3}-\d{4})$
| Part | Meaning |
|---|---|
^ |
Start of the string |
( ) |
Capture group — grab this part separately |
\d |
Any digit (0–9) |
{3} |
Exactly 3 of the previous character |
- |
A literal hyphen character |
$ |
End of the string |
Plain English: This pattern matches a US phone number in the format 555-867-5309, and captures the area code and the rest of the number as separate groups.
What Is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern. You use that pattern to:
- Test whether a string matches a format (email validation, form input checking)
- Find specific text inside a larger document (log analysis, search and replace)
- Extract parts of a string (pulling all URLs from HTML, scraping timestamps)
- Replace matched text with something else (reformatting dates, sanitizing input)
Regex is built into almost every programming language — JavaScript, Python, Go, Rust, PHP, Java — and into tools like grep, VS Code Find & Replace, and sed.
The Core Building Blocks
1. Literal Characters
The simplest regex is just a word. The pattern cat matches the exact sequence of characters c, a, t anywhere inside a string.
- Input:
"The cat sat on the mat"— matchescat - Input:
"concatenate"— also matches thecatinside it - Input:
"dog"— no match
2. The Dot . — Match Any Single Character
A . matches any single character except a newline.
| Pattern | Matches | Does Not Match |
|---|---|---|
c.t |
cat, cut, cot, c3t |
ct, coat |
b..k |
book, bark, b12k |
bk, back |
To match a literal dot, escape it: \. matches . only.
3. Character Classes [ ] — Match One of Several
Square brackets define a set of allowed characters. The pattern matches one character from the set.
| Pattern | Matches | Does Not Match |
|---|---|---|
[aeiou] |
Any single vowel | Consonants, digits |
[a-z] |
Any lowercase letter | Uppercase, digits |
[A-Z0-9] |
Any uppercase letter or digit | Lowercase, symbols |
[^aeiou] |
Any character that is NOT a vowel | Vowels |
4. Shorthand Character Classes
| Shorthand | Equivalent | Matches |
|---|---|---|
\d |
[0-9] |
Any digit |
\D |
[^0-9] |
Any non-digit |
\w |
[a-zA-Z0-9_] |
Letters, digits, underscore |
\W |
[^a-zA-Z0-9_] |
Spaces, symbols |
\s |
[ \t\n\r\f] |
Any whitespace |
\S |
[^ \t\n\r\f] |
Any non-whitespace |
5. Quantifiers — How Many Times?
| Quantifier | Meaning | Example | Matches |
|---|---|---|---|
? |
0 or 1 (optional) | colou?r |
color, colour |
* |
0 or more | ab*c |
ac, abc, abbbbc |
+ |
1 or more | ab+c |
abc, abbc (not ac) |
{n} |
Exactly n | \d{4} |
2026, 0001 |
{n,m} |
Between n and m | \d{2,4} |
12, 123, 1234 |
{n,} |
n or more | \d{3,} |
123, 4567, 999999 |
6. Anchors — Where in the String?
| Anchor | Meaning |
|---|---|
^ |
Start of the string |
$ |
End of the string |
\b |
Word boundary |
Example: \bcat\b matches cat in "the cat sat" but NOT in "concatenate". The pattern ^\d{5}$ matches exactly a 5-digit ZIP code and rejects 123456 or 1234.
7. Groups and Alternation
Parentheses ( ) group parts of a pattern and capture the matched text. The pipe | means “or.”
| Pattern | Matches |
|---|---|
(cat|dog) |
cat or dog |
(19|20)\d{2} |
Years 1900–1999 or 2000–2099 |
Non-capturing groups (?:...) group without capturing — useful when you only need the quantifier, not the value.
8. Flags (Modifiers)
| Flag | Effect |
|---|---|
i |
Case-insensitive matching |
g |
Global — find all matches, not just the first |
m |
Multiline — ^ and $ match each line |
s |
Dotall — . also matches newline characters |
5 Practical Patterns You Can Use Today
Pattern 1: Email Address Validation
^[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}$
| Input | Result |
|---|---|
user@example.com |
Match |
user.name+tag@sub.domain.io |
Match |
@missing-user.com |
No match |
user@.com |
No match |
Pattern 2: URL Detection
https?:\/\/[\w.-]+(?:\/[\w\-./?%&=]*)?
Matches http or https URLs, including paths and query strings.
Pattern 3: US Phone Number
^(\+1[-.\s]?)?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})$
| Input | Result |
|---|---|
555-867-5309 |
Match |
(555) 867-5309 |
Match |
+1 555.867.5309 |
Match |
5558675309 |
Match |
867-5309 |
No match (missing area code) |
Pattern 4: Hex Color Code
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
Matches both 6-digit (#2f5fd6) and 3-digit shorthand (#fff) hex colors.
Pattern 5: Extract Dates (YYYY-MM-DD)
\b(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\b
Smarter than \d{4}-\d{2}-\d{2} — it rejects impossible months like 13 or days like 45.
Common Mistakes Beginners Make
1. Forgetting to Escape Special Characters
These characters have special regex meaning: . * + ? ^ $ { } [ ] | ( ) \
To match them literally, escape with a backslash. The pattern 3.14 would match 3x14. The correct pattern is 3\.14.
2. Greedy vs. Lazy Matching
By default, quantifiers are greedy — they match as much as possible. Given <b>bold</b> and <i>italic</i>, the pattern <.+> greedily matches the entire string.
Add ? to make it lazy: <.+?> matches <b>, </b>, <i>, and </i> separately.
3. Anchoring Only One End
Pattern \d{5} matches 12345 inside abc12345xyz. Pattern ^\d{5}$ only matches strings that are exactly 5 digits. Always anchor patterns meant to validate a complete field.
4. Confusing \d with [0-9] in Unicode Contexts
In some engines, \d can match digits from other Unicode scripts. If you want strictly ASCII digits, use [0-9] explicitly.
Regex in JavaScript: Quick Reference
// Test if a string matches
/^\d{5}$/.test("90210"); // true
// Find the first match
"Call 555-1234 or 800-5678".match(/\d{3}-\d{4}/);
// ["555-1234"]
// Find ALL matches
"Call 555-1234 or 800-5678".match(/\d{3}-\d{4}/g);
// ["555-1234", "800-5678"]
// Replace matches
"2026-10-19".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1");
// "19/10/2026"
// Named capture groups
const match = "2026-10-19".match(/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/);
match.groups.year; // "2026"
match.groups.month; // "10"
Regex in Python: Quick Reference
import re
# Test if a pattern matches
re.match(r"^\d{5}$", "90210") # Match object (truthy)
re.match(r"^\d{5}$", "9021X") # None (falsy)
# Find all matches
re.findall(r"\d{3}-\d{4}", "Call 555-1234 or 800-5678")
# ["555-1234", "800-5678"]
# Extract groups
m = re.search(r"(\d{4})-(\d{2})-(\d{2})", "Date: 2026-10-19")
m.group(1) # "2026"
# Replace
re.sub(r"\s+", " ", "too many spaces")
# "too many spaces"
How to Build a Regex Pattern Step by Step
- Write a plain-English description of what you want to match.
- Start with the simplest version that handles the basic case.
- Test against real examples — both inputs that should match and inputs that must not.
- Tighten constraints where you find false positives or false negatives.
- Check edge cases: empty strings, Unicode characters, very long inputs.
Frequently Asked Questions
What does .* mean in regex?
It means “zero or more of any character.” The . matches any single character (except newline), and * means zero or more repetitions. It is essentially a wildcard that also matches empty strings. Use it carefully — it is greedy by default and can produce unexpected over-matches.
What is the difference between match() and search() in Python?
re.match() only checks for a match at the beginning of the string. re.search() scans the entire string for the first location where the pattern matches. For most use cases, re.search() is what you want.
How do I make a regex pattern case-insensitive?
Add the i flag. In JavaScript: /pattern/i. In Python: re.search(r"pattern", text, re.IGNORECASE). This makes [a-z] also match uppercase letters without writing [a-zA-Z].
Can regex validate complex formats like URLs perfectly?
Not reliably. A complete URL validator per RFC 3986 would require an extremely long pattern. For production use, prefer a dedicated URL-parsing library and use regex only for basic sanity checks or extraction from larger text.
What is a capture group and when do I need one?
A capture group — marked by ( ) — lets you isolate and extract a specific part of a match. Use them when you need to reference, reuse, or programmatically access a subsection of the matched text, such as extracting the year from a date string.
Is there a difference between regex in JavaScript and Python?
The core syntax is largely the same. Key differences: Python uses (?P<name>...) for named groups; JavaScript uses (?<name>...). Python also has limitations on variable-length lookbehinds in older versions. For beginner-level patterns, both behave identically.
How do I match a newline character?
Use \n to match a literal newline. In JavaScript, enable the s (dotall) flag so . also matches newlines. In Python, pass re.DOTALL as a flag to re.search() or re.match().
Practice These Patterns Now
The fastest way to learn regex is to test patterns interactively against real strings. Use the DwellixTools Regex Tester to paste any pattern from this guide, enter your own test inputs, and see matches highlighted in real time — with a built-in syntax cheatsheet always within reach.
Related Tools
Free browser tools related to this guide. Process locally with zero sign-up.
Regex Tester & Code Generator
Test regular expressions with live match highlighting, interactive cheatsheet, and code generators.
JSON Formatter & Validator
Format, validate, beautify, and minify JSON data instantly with real-time error detection.
HTML, CSS & JS Live Playground
Live interactive web code editor & sandboxed preview playground with real-time console log interceptor.