.* Text Processing

Common Regex Patterns — Copy-Paste Examples

Battle-tested regular expression patterns for email validation, IP matching, URL extraction, phone numbers, and more. Ready to use in any language.

Email Validation Regex

javascript

Validate email addresses with a practical regex pattern.

// Practical email regex (covers 99% of real emails)
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

console.log(emailRegex.test('[email protected]'));     // true
console.log(emailRegex.test('[email protected]')); // true
console.log(emailRegex.test('invalid@'));              // false
console.log(emailRegex.test('@no-user.com'));          // false

// Extract all emails from text
const text = 'Contact us at [email protected] or [email protected]';
const emails = text.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g);
console.log(emails); // ["[email protected]", "[email protected]"]

Email Validation Regex in Python

python

Validate and extract emails using Python's re module.

import re

pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

# Validate
print(re.match(pattern, '[email protected]'))  # Match object
print(re.match(pattern, 'invalid@'))           # None

# Extract all emails from text
text = 'Contact [email protected] or [email protected]'
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
print(emails)  # ['[email protected]', '[email protected]']

IPv4 Address Validation Regex

javascript

Match valid IPv4 addresses (0.0.0.0 to 255.255.255.255).

// Strict IPv4 (validates 0-255 range)
const ipv4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;

console.log(ipv4.test('192.168.1.1'));   // true
console.log(ipv4.test('10.0.0.0'));      // true
console.log(ipv4.test('256.1.1.1'));     // false (256 > 255)
console.log(ipv4.test('1.2.3'));         // false

// Extract IPs from log text
const log = 'Connection from 192.168.1.1 and 10.0.0.5 failed';
const ips = log.match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g);
console.log(ips); // ["192.168.1.1", "10.0.0.5"]

URL Matching Regex

javascript

Match and extract URLs from text.

// Match HTTP/HTTPS URLs
const urlRegex = /https?:\/\/[^\s<>"']+/gi;

const text = 'Visit https://example.com/path?q=1 or http://test.org';
const urls = text.match(urlRegex);
console.log(urls);
// ["https://example.com/path?q=1", "http://test.org"]

// Validate a URL with more structure
const strictUrl = /^https?:\/\/(?:www\.)?[a-zA-Z0-9-]+(?:\.[a-zA-Z]{2,})+(?:\/[^\s]*)?$/;
console.log(strictUrl.test('https://www.example.com/path'));  // true
console.log(strictUrl.test('ftp://invalid.com'));              // false

Phone Number Regex Patterns

javascript

Match various phone number formats.

// US phone numbers (multiple formats)
const usPhone = /^(?:\+1)?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;

console.log(usPhone.test('(555) 123-4567'));    // true
console.log(usPhone.test('+1-555-123-4567'));   // true
console.log(usPhone.test('555.123.4567'));      // true
console.log(usPhone.test('5551234567'));        // true

// International format (E.164)
const e164 = /^\+[1-9]\d{1,14}$/;
console.log(e164.test('+14155551234'));  // true
console.log(e164.test('+380501234567')); // true

Password Strength Validation Regex

javascript

Validate password complexity requirements.

// At least 8 chars, 1 uppercase, 1 lowercase, 1 digit, 1 special char
const strongPwd = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;

console.log(strongPwd.test('Passw0rd!'));  // true
console.log(strongPwd.test('weak'));        // false
console.log(strongPwd.test('NoSpecial1')); // false

// Individual checks (better UX)
function checkPassword(pwd) {
  return {
    length: pwd.length >= 8,
    uppercase: /[A-Z]/.test(pwd),
    lowercase: /[a-z]/.test(pwd),
    digit: /\d/.test(pwd),
    special: /[@$!%*?&#]/.test(pwd),
  };
}

Date Format Regex Patterns

javascript

Match common date formats (YYYY-MM-DD, MM/DD/YYYY, etc.).

// ISO 8601 date (YYYY-MM-DD)
const isoDate = /^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/;
console.log(isoDate.test('2024-01-15'));  // true
console.log(isoDate.test('2024-13-01'));  // false (month 13)

// US format (MM/DD/YYYY)
const usDate = /^(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12]\d|3[01])\/\d{4}$/;
console.log(usDate.test('01/15/2024'));  // true

// ISO 8601 datetime with timezone
const isoDateTime = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/;
console.log(isoDateTime.test('2024-01-15T10:30:00Z'));       // true
console.log(isoDateTime.test('2024-01-15T10:30:00+05:30')); // true

Hex Color Code Regex

javascript

Match and validate CSS hex color codes.

// Match #RGB or #RRGGBB
const hexColor = /^#(?:[0-9a-fA-F]{3}){1,2}$/;

console.log(hexColor.test('#fff'));     // true
console.log(hexColor.test('#FF5733')); // true
console.log(hexColor.test('#GGGG'));   // false

// Extract all colors from CSS text
const css = 'color: #333; background: #FF5733; border: #000;';
const colors = css.match(/#[0-9a-fA-F]{3,8}/gi);
console.log(colors); // ["#333", "#FF5733", "#000"]

URL Slug Validation Regex

javascript

Validate and generate URL-safe slugs.

// Validate a slug
const slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

console.log(slugRegex.test('my-blog-post'));     // true
console.log(slugRegex.test('post-123'));          // true
console.log(slugRegex.test('Invalid Slug'));      // false
console.log(slugRegex.test('-leading-dash'));     // false

// Generate a slug from a title
function slugify(text) {
  return text
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9\s-]/g, '')
    .replace(/[\s-]+/g, '-')
    .replace(/^-+|-+$/g, '');
}

console.log(slugify('Hello World! This is a Test'));
// "hello-world-this-is-a-test"

Credit Card Number Regex

javascript

Detect and validate credit card number formats.

// Specific card types
const visa = /^4\d{12}(?:\d{3})?$/;
const mastercard = /^5[1-5]\d{14}$/;
const amex = /^3[47]\d{13}$/;

// Strip spaces/dashes before validation
function validateCard(number) {
  const clean = number.replace(/[\s-]/g, '');
  return {
    visa: visa.test(clean),
    mastercard: mastercard.test(clean),
    amex: amex.test(clean),
  };
}

console.log(validateCard('4111 1111 1111 1111')); // visa: true
console.log(validateCard('5500-0000-0000-0004')); // mastercard: true

HTML Tag Extraction Regex

javascript

Extract and strip HTML tags from text.

// Strip all HTML tags
const html = '<p>Hello <strong>World</strong>!</p>';
const text = html.replace(/<[^>]*>/g, '');
console.log(text); // "Hello World!"

// Extract specific tag content
const imgRegex = /<img[^>]+src="([^"]+)"[^>]*>/gi;
const page = '<img src="photo.jpg" alt="Photo"> text <img src="logo.png">';
let match;
while ((match = imgRegex.exec(page)) !== null) {
  console.log(match[1]); // "photo.jpg", "logo.png"
}

Common Regex Operations in Python

python

Python re module: match, search, findall, sub, and named groups.

import re

text = "Order #123 shipped on 2024-01-15 to [email protected]"

# Find all numbers
numbers = re.findall(r'\d+', text)
print(numbers)  # ['123', '2024', '01', '15']

# Named groups
pattern = r'Order #(?P<order>\d+) shipped on (?P<date>[\d-]+)'
match = re.search(pattern, text)
if match:
    print(match.group('order'))  # '123'
    print(match.group('date'))   # '2024-01-15'

# Replace with regex
cleaned = re.sub(r'\b\d{4}-\d{2}-\d{2}\b', '[DATE]', text)
print(cleaned)

# Compile for reuse (faster)
email_re = re.compile(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}')
print(email_re.findall(text))  # ['[email protected]']

Regex in Go

go

Use the regexp package for pattern matching in Go.

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // Compile a pattern
    emailRe := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)

    text := "Contact [email protected] or [email protected]"

    // Find all matches
    emails := emailRe.FindAllString(text, -1)
    fmt.Println(emails) // [[email protected] [email protected]]

    // Replace
    masked := emailRe.ReplaceAllString(text, "[EMAIL]")
    fmt.Println(masked) // "Contact [EMAIL] or [EMAIL]"
}

UUID Validation Regex

javascript

Validate UUID v4 format strings.

// UUID v4 pattern
const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

console.log(uuidV4.test('550e8400-e29b-41d4-a716-446655440000')); // true
console.log(uuidV4.test('not-a-uuid')); // false

// Any UUID version
const uuidAny = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

// Extract UUIDs from text
const log = 'User 550e8400-e29b-41d4-a716-446655440000 created session abc123';
const uuids = log.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi);
console.log(uuids);

Whitespace Cleanup Regex Patterns

javascript

Clean up whitespace: trim, collapse, normalize line endings.

// Collapse multiple spaces to one
const text = 'hello    world   foo';
console.log(text.replace(/\s+/g, ' ')); // "hello world foo"

// Trim leading/trailing whitespace per line
const multiline = '  hello  \n  world  ';
console.log(multiline.replace(/^\s+|\s+$/gm, ''));
// "hello\nworld"

// Remove blank lines
const withBlanks = 'line1\n\n\nline2\n\nline3';
console.log(withBlanks.replace(/\n{2,}/g, '\n'));
// "line1\nline2\nline3"

// Normalize line endings (\r\n -> \n)
const mixed = 'line1\r\nline2\rline3\n';
console.log(mixed.replace(/\r\n?/g, '\n'));

Need to work with regex patterns for email, ip, url, phone & more right now?

Use our free online regex tester — no signup, no install, works in your browser.

Open Regex Tester →

More Code Snippets