Regex Examples and Cookbook

Large cookbook of validation, extraction, cleanup, and code-search regex recipes for everyday engineering work.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Validation Recipes
UUID shape
^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$

# Match a standard hyphenated UUID.

IPv4 address
^(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$

# Match an IPv4 address with octet range checks.

Domain name
^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$

# Match a basic domain or subdomain name.

Hex color
^#(?:[0-9A-Fa-f]{3}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$

# Match CSS hex colors.

Semantic version
^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$

# Match a semantic version string.

ISO date shape
^\d{4}-\d{2}-\d{2}$

# Match a simple YYYY-MM-DD date shape.

## Extraction Recipes
Extract URLs
https?://[^\s<>"']+

# Find basic HTTP or HTTPS URLs.

Extract emails
\b[^\s@]+@[^\s@]+\.[^\s@]+\b

# Find email-like tokens in text.

Capture a simple CSV field
[^,]+

# Extract a non-quoted CSV field token.

Extract fenced code block
```(\w+)?
[\s\S]*?
```

# Match a markdown fenced code block.

Extract log level
\b(INFO|WARN|WARNING|ERROR|DEBUG|TRACE|FATAL)\b

# Capture common log levels from log lines.

## Cleanup and Normalization
Match Windows line endings
\r

# Find CRLF line endings.

Collapse blank lines
(?:\r?
\s*){3,}

# Match repeated blank lines.

Match leading or trailing spaces per line
^\s+|\s+$

# Trim each line in multiline mode.

Strip simple HTML-like tags
</?[^>]+>

# Match simple HTML tags for rough removal.

Normalize phone separators
[-.\s()]

# Match common phone separators.

Redact card-like numbers
\b(?:\d{4}[- ]?){3}\d{4}\b

# Find common 16-digit card-like sequences with separators.

## Language and Data Format Recipes
JSON key capture
"([^"\\]+)"\s*:

# Capture a simple JSON object key.

YAML key shape
^[A-Za-z0-9_.-]+:

# Match a simple YAML key at the start of a line.

Find SELECT *
(?i)\bselect\s+\*\s+from\b

# Find SQL `SELECT *` usage.

Capture HTML id attribute
\bid=["\']([^"\']+)["\']

# Capture an HTML `id` value.

CSS class selector
\.[A-Za-z_-][A-Za-z0-9_-]*

# Match a simple CSS class selector.

Environment variable assignment
^[A-Za-z_][A-Za-z0-9_]*=.*$

# Match `.env`-style key=value lines.

Recommended next

No recommendations yet.