1. What Are Regular Expressions?
Regular expressions (regex or regexp) are a powerful pattern-matching language used to search, match, and manipulate text. Think of them as a supercharged "Find & Replace" that can match complex patterns instead of just exact words.
Regex is used everywhere in software development:
- Search & Replace — find and transform text in editors and IDEs
- Form Validation — check if user input matches expected formats (email, phone, URL)
- Data Extraction — pull specific information from logs, HTML, CSV files
- Routing — match URL paths in web frameworks (Express, Django, Flask)
- Log Analysis — filter and parse server logs with tools like grep
Nearly every programming language supports regex: JavaScript, Python, Java, C#, Go, Rust, PHP, Ruby, and more. The syntax is almost identical across all of them.
2. Regex Basics
A regex pattern is a sequence of characters that defines a search pattern. Some characters match themselves (literals), while others have special meanings (metacharacters).
Literal Characters
The simplest regex matches exact text. The pattern hello matches the word "hello" anywhere in a string:
"hello world" → match: "hello"
"say hello!" → match: "hello"
"HELLO" → no match (case-sensitive by default)
Special Characters (Metacharacters)
These characters have special meaning in regex and must be escaped with \ to match them literally:
| Character | Meaning | Example |
|---|---|---|
. |
Any single character (except newline) | a.c matches "abc", "a1c", "a-c" |
* |
Zero or more of the preceding element | ab*c matches "ac", "abc", "abbc" |
+ |
One or more of the preceding element | ab+c matches "abc", "abbc" (not "ac") |
? |
Zero or one of the preceding element | colou?r matches "color" and "colour" |
[] |
Character class — match any one character inside | [aeiou] matches any vowel |
{} |
Repetition — specify exact quantity | \d{3} matches exactly 3 digits |
() |
Grouping — treat as a single unit | (ha)+ matches "ha", "haha", "hahaha" |
^ |
Start of string (or negate in []) |
^Hello matches "Hello" at string start |
$ |
End of string | end$ matches "end" at string end |
\ |
Escape the next character | \. matches a literal dot "." |
Character Classes (Shorthand)
Instead of writing long character sets, use these shortcuts:
| Shorthand | Matches | Equivalent |
|---|---|---|
\d |
Any digit (0-9) | [0-9] |
\D |
Any non-digit | [^0-9] |
\w |
Word character (letter, digit, underscore) | [a-zA-Z0-9_] |
\W |
Non-word character | [^a-zA-Z0-9_] |
\s |
Whitespace (space, tab, newline) | [ \t\n\r\f] |
\S |
Non-whitespace | [^ \t\n\r\f] |
For example, \d{3}-\d{4} matches a phone-like pattern such as "555-1234".
3. Quantifiers and Anchors
Quantifiers control how many times a pattern should match. Anchors control where a match occurs.
Quantifiers
| Quantifier | Description | Example |
|---|---|---|
* |
0 or more (greedy) | ab*c → "ac", "abc", "abbbc" |
+ |
1 or more (greedy) | ab+c → "abc", "abbbc" (not "ac") |
? |
0 or 1 (optional) | https? → "http" or "https" |
{n} |
Exactly n times | \d{4} → exactly 4 digits |
{n,} |
n or more times | \d{2,} → 2 or more digits |
{n,m} |
Between n and m times | \d{2,4} → 2, 3, or 4 digits |
*? +? |
Lazy versions (match as few as possible) | a.*?b → "aab" in "aabcb" |
Anchors and Boundaries
| Anchor | Description | Example |
|---|---|---|
^ |
Start of string | ^Hello matches only at the beginning |
$ |
End of string | world$ matches only at the end |
\b |
Word boundary | \bcat\b matches "cat" but not "catch" |
\B |
Non-word boundary | \Bcat matches "cat" in "concatenate" |
Combine quantifiers with anchors for precise matching. For example, ^\d{5}$ matches a string that is exactly a 5-digit ZIP code and nothing else.
4. Groups and Capturing
Parentheses () serve two purposes: grouping patterns together and capturing matched text for later use.
Capturing Groups
Each pair of parentheses creates a numbered capture group. You can reference the captured text later:
// Pattern: (\d{4})-(\d{2})-(\d{2})
// Input: "2026-07-20"
// Group 1: "2026" (year)
// Group 2: "07" (month)
// Group 3: "20" (day)
// In JavaScript:
const match = "2026-07-20".match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(match[1]); // "2026"
console.log(match[2]); // "07"
console.log(match[3]); // "20"
Non-Capturing Groups
Use (?:) when you need grouping for quantifiers but do not need to capture the matched text:
// With capturing group (stores "https" or "http"):
/^(https?:)\/\/example\.com$/
// With non-capturing group (groups but does not store):
/^(?:https?:)\/\/example\.com$/
// Non-capturing is slightly more efficient
// and avoids cluttering your capture groups
Backreferences
Use \1, \2, etc. to refer back to a previously captured group. This is useful for matching repeated words:
// Find repeated words:
/(\b\w+\b)\s+\1/
// Matches: "the the", "is is", "hello hello"
// Does not match: "the a", "hello world"
// Example in JavaScript:
"the the cat".match(/(\b\w+\b)\s+\1/);
// Match: "the the", Group 1: "the"
Named Groups
Modern regex supports named groups with (?<name>...) for more readable patterns:
// Named groups for a date pattern:
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
// In JavaScript:
const result = "2026-07-20".match(
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
);
console.log(result.groups.year); // "2026"
console.log(result.groups.month); // "07"
console.log(result.groups.day); // "20"
Want to test capture groups interactively?
Open Regex Tester →5. Real-World Examples
Here are practical regex patterns you will use regularly. Each one includes a step-by-step breakdown so you understand every part of the pattern.
Email Address
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
^— start of string[a-zA-Z0-9._%+-]+— one or more allowed characters for the local part@— literal @ symbol[a-zA-Z0-9.-]+— domain name (letters, digits, dots, hyphens)\.[a-zA-Z]{2,}— dot followed by 2+ letter TLD (.com, .org, .io)$— end of string
// Valid matches:
"[email protected]", "[email protected]"
// Does not match:
"@missing.com", "user@", "[email protected]"
URL
/https?:\/\/(www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(\/[^\s]*)?/
https?:— "http:" or "https:"\/\/— literal "//"(www\.)?— optional "www."[a-zA-Z0-9-]+— domain name\.[a-zA-Z]{2,}— TLD (.com, .org, etc.)(\/[^\s]*)?— optional path (any non-whitespace after /)
Phone Number (US Format)
/^(\+1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/
(\+1[-.\s]?)?— optional country code "+1" with optional separator\(?\d{3}\)?— area code, with optional parentheses[-.\s]?\d{3}— 3-digit prefix with optional separator[-.\s]?\d{4}— 4-digit line number
// Matches: "(555) 123-4567", "555-123-4567", "+1.555.123.4567"
IPv4 Address
/^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
Each octet uses the same sub-pattern: 25[0-5] (250-255), 2[0-4]\d (200-249), or [01]?\d\d? (0-199). This ensures only valid IP addresses match.
// Valid: "192.168.1.1", "10.0.0.255", "255.255.255.0"
// Invalid: "256.1.1.1", "192.168.1", "10.0.0.0.1"
Date Format (YYYY-MM-DD)
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/
\d{4}— 4-digit year(0[1-9]|1[0-2])— month: 01-12(0[1-9]|[12]\d|3[01])— day: 01-31
// Valid: "2026-07-20", "2000-01-01", "1999-12-31"
// Invalid: "2026-13-01", "2026-00-15", "2026-07-32"
Try these patterns in a live regex tester:
Open Regex Tester →6. Practice with Online Tester
The best way to learn regex is by experimenting. Our free Regex Tester tool lets you write patterns and see matches in real time.
Step-by-Step Guide
- Open the Regex Tester — navigate to /tools/regex-tester.html
- Enter your test text — paste any text you want to search in the input area
- Write your pattern — type your regex in the pattern field (no slashes needed)
- Choose flags — enable
g(global) to find all matches,i(case-insensitive), orm(multiline) - See highlights — matches are highlighted in the text instantly as you type
- View groups — capture groups are listed below so you can inspect each part
Practice Exercises
Try these exercises to build your regex skills:
- Find all numbers in a paragraph — pattern:
\d+ - Extract hashtags from social media text — pattern:
#\w+ - Validate an email — use the email pattern from Section 5
- Match HTML tags — pattern:
<\/?[a-z][a-z0-9]*> - Find repeated words — use the backreference pattern:
(\b\w+\b)\s+\1
Quick Reference: Common Flags
| Flag | Name | Description |
|---|---|---|
g |
Global | Find all matches, not just the first |
i |
Case Insensitive | Ignore uppercase/lowercase differences |
m |
Multiline | ^ and $ match start/end of each line |
s |
Dot All | . also matches newline characters |
Ready to write your first regex? Start practicing now!
Launch Regex Tester →