Introduction
Real-world regex applications include data validation, log parsing, and text transformation. These practical examples demonstrate how regex solves common programming tasks.
Email Validation
# Simple email pattern
/^[w.-]+@[w.-]+.w{2,}$/
# More comprehensive
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.{2,}$/
# JavaScript validation
function isValidEmail(email) {
return /^[^s@]+@[^s@]+.[^s@]+$/.test(email);
}
URL Parsing
# Extract URL components
/^(https?)://([w.-]+)(:d+)?(/.*)?$/
# Match and extract
const url = "https://example.com:8080/path";
const match = url.match(/^(https?)://([w.-]+)(?::(d+))?(/.*)?$/);
// protocol: "https", host: "example.com", port: "8080", path: "/path"
Log Parsing
# Parse Apache log format
/^(S+) S+ S+ [([^]]+)] "(S+) (S+) S+" (d{3})/
# Extract fields
const log = '192.168.1.1 - - [12/Jun/2024] "GET /api HTTP/1.1" 200';
const m = log.match(/^(S+) .+[(.+?)] "(w+) (S+)/);
// IP, date, method, path
Text Replacement
# JavaScript: replace all occurrences
"hello world".replace(/world/, "JavaScript")
# Python: re.sub
import re
result = re.sub(r'bfoob', 'bar', 'foo baz foo')
# Format phone numbers
"(555) 123-4567".replace(/D/g, '')
.replace(/(d{3})(d{3})(d{4})/, '($1) $2-$3')
Common Patterns
# IP address
/^(d{1,3}.){3}d{1,3}$/
# Date (YYYY-MM-DD)
/^d{4}-(0|1)-(0|d|3)$/
# HTML tags
/</?+[^>]*>/g
Summary
Regex is invaluable for validation, parsing, and transformation. Build patterns incrementally, test thoroughly, and use online tools like regex101.com for debugging.
YouTip