8. Regex Examples
A cookbook of real-world patterns
Theory is done. This article is a reference — a large collection of practical regex patterns you'll encounter in real work. Each pattern is explained piece by piece so you can adapt it to your needs.
Use the Regex Tester below to try any pattern from this page — or write your own.
Regex Tester
Validation Patterns
Email Address (Simplified)
Pattern
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Breakdown
^— start of string[a-zA-Z0-9._%+-]+— local part: letters, digits, dots, underscores, percent, plus, hyphen@— literal at-sign[a-zA-Z0-9.-]+— domain: letters, digits, dots, hyphens\.— literal dot before TLD[a-zA-Z]{2,}— TLD: at least 2 letters$— end of string
Matches
[email protected]
[email protected]
Does NOT match
@example.com
[email protected]
user@com
Caveat
Truly validating email with regex is notoriously hard. The full RFC 5322 spec allows quoted strings, comments, and IP address literals. This pattern covers 99% of real-world addresses. For production, use your language's email validation library.
URL
Pattern
^https?://[^\s/$.?#].[^\s]*$
Breakdown
https?://— protocol (http or https)[^\s/$.?#]— first character of domain (not whitespace or special URL chars).— any character[^\s]*— rest of URL (no whitespace)
Matches
https://example.com
http://example.com/path?query=1#section
IPv4 Address
Pattern
^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$
Breakdown
25[0-5]— matches 250-2552[0-4]\d— matches 200-249[01]?\d\d?— matches 0-199- The whole octet group repeats 3 times with a dot, then once without
Matches
192.168.1.1
10.0.0.255
255.255.255.0
Does NOT match
256.1.1.1
192.168.1
192.168.1.1.1
Date (YYYY-MM-DD)
Pattern
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
Breakdown
\d{4}— four-digit year(0[1-9]|1[0-2])— month 01-12(0[1-9]|[12]\d|3[01])— day 01-31
Matches
2026-04-24
2000-12-31
Does NOT match
2026-13-01
2026-00-15
Caveat
This doesn't validate that the day is valid for the month (e.g., Feb 30). Use a date library for full validation.
Time (HH:MM, 24-hour)
Pattern
^([01]\d|2[0-3]):[0-5]\d$
Matches
00:00, 14:30, 23:59
Does NOT match
24:00, 12:60
Password Strength
Pattern
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$
Requirements
- At least one lowercase letter
- At least one uppercase letter
- At least one digit
- At least one special character from
@$!%*?& - Minimum 8 characters
Hex Color Code
Pattern
^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
Matches
#fff, #FFF, #a1b2c3, #000000
Does NOT match
#gg0000, #12345, fff
Extraction Patterns
Phone Numbers (US)
Pattern
(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}
Matches
(555) 123-4567
555-123-4567
+1 555.123.4567
5551234567
Extract HTML Tags
Pattern
<([a-z][a-z0-9]*)\b[^>]*>(.*?)\1>
Breakdown
<([a-z][a-z0-9]*)— opening tag name (captured in group 1)\b[^>]*>— optional attributes, then closing>(.*?)— tag contents (lazy, captured in group 2)\1>— closing tag matching group 1
Matches
<b>bold</b> → group 1: "b", group 2: "bold"
<span class="x">text</span> → group 1: "span", group 2: "text"
Caveat
Don't use regex to parse arbitrary HTML. This works for simple, well-formed, non-nested tags. For real HTML, use a proper parser.
Extract Key-Value Pairs
Pattern
(\w+)\s*=\s*"([^"]*)"
Input
name="Alice" age="30" city="Paris"
Captures
Match 1: group 1 = "name", group 2 = "Alice"
Match 2: group 1 = "age", group 2 = "30"
Match 3: group 1 = "city", group 2 = "Paris"
Extract Markdown Links
Pattern
\[([^\]]+)\]\(([^)]+)\)
Input
Visit [Google](https://google.com) or [GitHub](https://github.com)
Captures
Match 1: group 1 = "Google", group 2 = "https://google.com"
Match 2: group 1 = "GitHub", group 2 = "https://github.com"
CSV Fields (Handling Quoted Commas)
Pattern
"([^"]*(?:""[^"]*)*)"|([^,]+)
Input
Alice,"New York, NY",30
Captures
Match 1: "Alice"
Match 2: "New York, NY" (quotes stripped via group 1)
Match 3: "30"
Log & Text Processing
Apache/Nginx Log Line
Pattern
^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+) \S+" (\d{3}) (\d+|-)
Input
192.168.1.1 - - [24/Apr/2026:10:15:30 +0000] "GET /index.html HTTP/1.1" 200 1234
Captures
- Group 1:
192.168.1.1(IP) - Group 2:
24/Apr/2026:10:15:30 +0000(timestamp) - Group 3:
GET(method) - Group 4:
/index.html(path) - Group 5:
200(status code) - Group 6:
1234(bytes)
Syslog Timestamp
Pattern
^([A-Z][a-z]{2})\s+(\d{1,2})\s+(\d{2}:\d{2}:\d{2})
Input
Apr 24 10:15:30 myhost sshd[1234]: message
Captures
Group 1: "Apr", Group 2: "24", Group 3: "10:15:30"
Stack Trace File References
Pattern
(?:at\s+)?(\S+)\s*\(([^:]+):(\d+):(\d+)\)
Input
at Object.main (src/index.ts:42:5)
Captures
Group 1: "Object.main"
Group 2: "src/index.ts"
Group 3: "42" (line)
Group 4: "5" (column)
Filter Lines Containing a Pattern
Pattern (with /gm flags)
^.*\b(ERROR|FATAL)\b.*$
What it does
Matches entire lines that contain "ERROR" or "FATAL" as standalone words.
Extract JSON String Values
Pattern
"(\w+)"\s*:\s*"([^"\\]*(?:\\.[^"\\]*)*)"
Input
{"name": "Alice", "message": "She said \"hello\""}
Captures
Match 1: group 1 = "name", group 2 = "Alice"
Match 2: group 1 = "message", group 2 = "She said \"hello\""
How it handles escapes
[^"\\]*(?:\\.[^"\\]*)* — matches non-quote, non-backslash chars, then
allows escaped characters (\\.) followed by more non-quote chars. This
correctly handles escaped quotes inside strings.
Search & Replace
Convert camelCase to snake_case
Find
([a-z])([A-Z])
Replace
$1_$2
Then lowercase the result
Examples
camelCase → camel_case
getUserName → get_user_name
parseJSON → parse_json
Convert snake_case to camelCase
Find
_([a-z])
Replace (with callback or \u modifier)
Uppercase the captured letter. In JavaScript:
str.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
Examples
snake_case → snakeCase
get_user_name → getUserName
Remove HTML Tags
Find
<[^>]+>
Replace
(empty string)
Input
<p>Hello <b>world</b></p>
Result
Hello world
Reformat Dates (MM/DD/YYYY → YYYY-MM-DD)
Find
(\d{2})/(\d{2})/(\d{4})
Replace
$3-$1-$2
Input → Output
04/24/2026 → 2026-04-24
Add Thousands Separators to Numbers
Pattern (lookahead approach)
\d{1,3}(?=(\d{3})+(?!\d))
Replace
$&,
Input → Output
1234567 → 1,234,567
How it works
The lookahead checks that the remaining digits come in groups of exactly three. The
negative lookahead (?!\d) ensures we don't match in the middle of a group.
Swap First and Last Name
Find
^(\w+)\s+(\w+)$
Replace
$2, $1
Input → Output
John Doe → Doe, John
Numbers & Math
Integer (with Optional Sign)
Pattern
^[+-]?\d+$
Matches
42, -7, +100, 0
Floating-Point Number
Pattern
^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$
Matches
3.14, -0.5, .75, 1e10, 2.5E-3, +42
Breakdown
[+-]?— optional sign\d+\.?\d*— digits, optional decimal point, optional more digits\.\d+— or: decimal point followed by digits (e.g.,.75)([eE][+-]?\d+)?— optional scientific notation
Currency Amount
Pattern
^\$\d{1,3}(,\d{3})*(\.\d{2})?$
Matches
$1.00, $42, $1,000, $1,000,000.99
Does NOT match
$1,00, $1000 (no comma), 42.00 (no $)
Percentage
Pattern
^\d+(\.\d+)?%$
Matches
100%, 42.5%, 0.1%
Code & Programming
Match Single-Line Comments
Pattern
//.*$|#.*$
Matches
// this is a comment
# this too
Match Multi-Line Comments
Pattern
/\*[\s\S]*?\*/
Matches
/* single line */
/* multi
line
comment */
Why [\s\S]?
[\s\S] matches any character including newlines. It's the classic
workaround for engines where . doesn't match \n by default.
Match String Literals
Pattern (double-quoted, with escape handling)
"([^"\\]|\\.)*"
Matches
"hello"
"say \"hi\""
"line1\nline2"
""
Breakdown
[^"\\] matches any char that's not a quote or backslash.
\\. matches a backslash followed by any char (an escape sequence). Together,
they correctly handle escaped quotes.
Match Function Definitions
Pattern (JavaScript/TypeScript)
(?:function\s+(\w+)|(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w]+)\s*=>)
Matches
function processData(...)
const fetchUser = async (id) =>
let compute = x =>
Match Import Statements
Pattern (JavaScript/TypeScript)
^import\s+(?:(?:\{[^}]*\}|\*\s+as\s+\w+|\w+)(?:\s*,\s*(?:\{[^}]*\}|\*\s+as\s+\w+|\w+))*\s+from\s+)?['"]([^'"]+)['"];?$
Matches
import { foo } from 'bar';
import * as utils from "utils";
import React, { useState } from 'react';
import './styles.css';
Find TODO/FIXME Comments
Pattern
(?://|#|/\*)\s*(?:TODO|FIXME|HACK|XXX)\b[:\s]*(.*?)(?:\*/)?$
Matches
// TODO: fix this later
# FIXME: race condition here
/* HACK: temporary workaround */
Text Cleaning
Collapse Multiple Spaces
Find
{2,}
Replace
Input → Output
too many spaces → too many spaces
Trim Leading/Trailing Whitespace
Find
^\s+|\s+$
Replace
(empty string)
Remove Blank Lines
Find (with /gm)
^\s*\n
Replace
(empty string)
Remove Duplicate Lines
Find (with /gm)
^(.+)$\n(?=[\s\S]*^\1$)
Replace
(empty string)
How it works
Captures a line, then uses a lookahead with backreference to check if the same line appears again later. If so, the first occurrence is removed.
Normalize Line Endings
Find
\r\n?
Replace
\n
What it does
Converts Windows (\r\n) and old Mac (\r) line endings to
Unix (\n).
Network & System
MAC Address
Pattern
^([0-9a-fA-F]{2}[:-]){5}[0-9a-fA-F]{2}$
Matches
00:1A:2B:3C:4D:5E
00-1a-2b-3c-4d-5e
UUID
Pattern
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$
Matches
550e8400-e29b-41d4-a716-446655440000
Semantic Version
Pattern
^v?(\d+)\.(\d+)\.(\d+)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?(?:\+([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?$
Matches
1.0.0
v2.1.3
1.0.0-alpha.1
1.0.0-beta+build.123
Captures
Group 1: major, Group 2: minor, Group 3: patch
Group 4: pre-release, Group 5: build metadata
File Path (Unix)
Pattern
^(/[^/\0]+)+/?$
Matches
/home/user/file.txt
/var/log/
/etc/nginx/nginx.conf
Domain Name
Pattern
^([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$
Matches
example.com
sub.domain.example.org
my-site.co.uk
Language-Specific Tips
JavaScript
// Literal syntax
const re = /pattern/flags;
// Constructor (for dynamic patterns)
const re = new RegExp("pattern", "flags");
// Common methods
str.match(re); // returns matches
str.replace(re, rep); // search and replace
str.split(re); // split by pattern
re.test(str); // returns boolean
re.exec(str); // returns match object with groups
// Named groups (ES2018+)
const { groups: { year, month } } = "2026-04".match(/(?<year>\d{4})-(?<month>\d{2})/);
// matchAll for global iteration (ES2020+)
for (const match of str.matchAll(/pattern/g)) {
console.log(match[0], match.groups);
}
Python
import re
# Compile for reuse
pattern = re.compile(r"pattern", re.IGNORECASE | re.MULTILINE)
# Common functions
re.search(r"pattern", text) # first match anywhere
re.match(r"pattern", text) # match at start only
re.findall(r"pattern", text) # all matches as list
re.finditer(r"pattern", text) # all matches as iterator
re.sub(r"find", r"replace", text) # search and replace
# Always use raw strings (r"...") to avoid backslash issues
Flags Reference
| Flag | JavaScript | Python | Meaning |
|---|---|---|---|
| Case-insensitive | i |
re.IGNORECASE |
A matches a |
| Global | g |
N/A (use findall) |
Find all matches |
| Multiline | m |
re.MULTILINE |
^/$ match line boundaries |
| Dotall | s |
re.DOTALL |
. matches \n |
| Unicode | u |
re.UNICODE |
Full Unicode support |
| Verbose | N/A | re.VERBOSE |
Allow comments and whitespace |
Quick Reference Card
| Need to... | Pattern |
|---|---|
| Match any character | . |
| Match a digit | \d |
| Match a word character | \w |
| Match whitespace | \s |
| Match start of string | ^ |
| Match end of string | $ |
| Match word boundary | \b |
| Match one of several chars | [abc] |
| Match a range | [a-z] |
| Negate a class | [^abc] |
| Zero or more | * |
| One or more | + |
| Optional | ? |
| Exactly n times | {n} |
| n to m times | {n,m} |
| Lazy quantifier | *? +? ?? |
| Capture group | (...) |
| Non-capturing group | (?:...) |
| Named group | (?<name>...) |
| Backreference | \1 or \k<name> |
| Positive lookahead | (?=...) |
| Negative lookahead | (?!...) |
| Positive lookbehind | (?<=...) |
| Negative lookbehind | (?<!...) |
| Alternation | a|b |
| Escape metacharacter | \ |