Common Regex Examples: Practical Patterns for Daily Development
Explore practical regex patterns you'll use regularly. Learn phone numbers, URLs, postal codes, and more.
Regex becomes powerful when you understand practical patterns used in real development. This guide showcases patterns you'll actually use.
Form Validation Examples
Username Validation
Usernames: 3-20 characters, alphanumeric and underscore only
function validateUsername(username) {
const regex = /^[a-zA-Z0-9_]{3,20}$/;
return regex.test(username);
}
console.log(validateUsername('john_doe')); // true
console.log(validateUsername('ab')); // false (too short)
console.log(validateUsername('user@name')); // false (invalid char)
Password Requirements
Strong password: 8+ chars, uppercase, lowercase, number, special char
function validateStrongPassword(password) {
const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
return regex.test(password);
}
console.log(validateStrongPassword('SecurePass123!')); // true
console.log(validateStrongPassword('weak')); // false
Text Extraction Examples
Extract URLs from Text
function extractUrls(text) {
const regex = /https?:\/\/[^\s]+/g;
return text.match(regex) || [];
}
const text = 'Visit https://example.com and http://test.org for more info';
console.log(extractUrls(text));
// ['https://example.com', 'http://test.org']
Extract Hashtags
function extractHashtags(text) {
const regex = /#[a-zA-Z0-9_]+/g;
return text.match(regex) || [];
}
const tweet = 'Love #JavaScript and #RegEx! #WebDevelopment rocks!';
console.log(extractHashtags(tweet));
// ['#JavaScript', '#RegEx', '#WebDevelopment']
Extract Mentions (@username)
function extractMentions(text) {
const regex = /@[a-zA-Z0-9_]+/g;
return text.match(regex) || [];
}
const comment = 'Hey @john_doe and @alice_smith, check this out!';
console.log(extractMentions(comment));
// ['@john_doe', '@alice_smith']
Data Cleaning Examples
Remove HTML Tags
function removeHtmlTags(html) {
return html.replace(/<[^>]*>/g, '');
}
const dirty = '<p>Hello <strong>World</strong>!</p>';
console.log(removeHtmlTags(dirty)); // 'Hello World!'
Remove Extra Whitespace
function normalizeWhitespace(text) {
return text.replace(/\s+/g, ' ').trim();
}
const messy = ' Hello World \n\t Regex ';
console.log(normalizeWhitespace(messy));
// 'Hello World Regex'
Capitalize Words
function capitalizeWords(text) {
return text.replace(/\b\w/g, char => char.toUpperCase());
}
console.log(capitalizeWords('hello world')); // 'Hello World'
Data Formatting Examples
Phone Number Formatter
function formatPhoneNumber(phone) {
const cleaned = phone.replace(/\D/g, '');
return cleaned.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}
console.log(formatPhoneNumber('5551234567')); // (555) 123-4567
console.log(formatPhoneNumber('555.123.4567')); // (555) 123-4567
Credit Card Number Formatter
function formatCreditCard(number) {
const cleaned = number.replace(/\D/g, '');
return cleaned.replace(/(\d{4})/g, '$1 ').trim();
}
console.log(formatCreditCard('1234567890123456'));
// '1234 5678 9012 3456'
Currency Formatting
function parseCurrency(value) {
const regex = /^\$?([0-9]+(\.?[0-9]{2})?)/;
const match = value.match(regex);
return match ? parseFloat(match[1]) : null;
}
console.log(parseCurrency('$99.99')); // 99.99
console.log(parseCurrency('1,234.50')); // null (has comma)
Search and Replace Examples
Replace Email with Masked Version
function maskEmail(email) {
return email.replace(/(.{2}).*(@.*)/, '$1***$2');
}
console.log(maskEmail('john@example.com'));
// 'jo***@example.com'
Convert Markdown Links
function markdownToHtml(text) {
return text.replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>');
}
const md = 'Click [here](https://example.com) for more';
console.log(markdownToHtml(md));
// 'Click <a href="https://example.com">here</a> for more'
Validation Examples
SNS Numbers
function validateSSN(ssn) {
return /^\d{3}-\d{2}-\d{4}$/.test(ssn);
}
console.log(validateSSN('123-45-6789')); // true
console.log(validateSSN('12345678')); // false
Hex Color Codes
function isHexColor(color) {
return /^#(?:[0-9a-fA-F]{3}){1,2}$/.test(color);
}
console.log(isHexColor('#ff00ff')); // true
console.log(isHexColor('#f0f')); // true
console.log(isHexColor('ff00ff')); // false (missing #)
Real-World API Response Parsing
Extract JSON Errors
function extractErrorMessages(response) {
const regex = /"error"\s*:\s*"([^"]*)"/g;
const errors = [];
let match;
while ((match = regex.exec(response)) !== null) {
errors.push(match[1]);
}
return errors;
}
const apiResponse = '{"error": "Invalid email", "meta": {"error": "Rate limit"}}';
console.log(extractErrorMessages(apiResponse));
// ['Invalid email', 'Rate limit']
Performance Considerations
For repeated operations, compile regex once:
// ❌ Creates new regex each time
function process(items) {
return items.map(item => item.replace(/pattern/, 'replacement'));
}
// ✓ Reuse compiled regex
const pattern = /pattern/;
function process(items) {
return items.map(item => item.replace(pattern, 'replacement'));
}
Testing Framework
function testPattern(regex, cases) {
cases.forEach(({ input, expected }) => {
const result = regex.test(input);
const status = result === expected ? '✓' : '✗';
console.log(`${status} ${input} => ${result}`);
});
}
const phoneRegex = /^\d{10}$/;
testPattern(phoneRegex, [
{ input: '5551234567', expected: true },
{ input: '555-123-4567', expected: false },
{ input: '555123456', expected: false },
]);
These practical examples demonstrate regex solving real problems. Start with simple patterns and gradually build more complex ones as needed. Remember: the simplest regex that solves your problem is the best choice.
Average reading pace: 200 words per minute
Share Article
Related Articles
Regex for Email Validation: Building Robust Patterns
Learn how to create reliable email validation patterns using regular expressions. Explore different approaches and their trade-offs.
Regex for Numbers Only: Extracting and Validating Numeric Data
Master regex patterns for working with numbers. Learn to extract, validate, and filter numeric data from strings.
Comprehensive Regex Cheat Sheet: Syntax and Examples
A complete reference guide for regular expressions. Contains all essential patterns, flags, and examples for quick lookup.