Regex Patterns Every Developer Needs

Regular expressions feel like magic β€” or black magic β€” depending on the day. Here is a curated collection of patterns you will actually use.

Email Validation

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

Covers the vast majority of real-world email addresses. Does not attempt to be RFC 5321-complete β€” if you need that, use a dedicated library.

URL Matching

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

Matches http and https URLs. Use with the gi flags to find all URLs in a block of text.

Phone Numbers (International)

^\+?[1-9]\d{1,14}$

E.164 format β€” the international standard. For country-specific formats, you need per-country patterns or the libphonenumber library.

Chinese Mobile Numbers

^1[3-9]\d{9}$

Matches all current Chinese mobile number prefixes (13x–19x).

Semantic Version (semver)

^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$

The official semver.org-conformant regex. Handles pre-release labels and build metadata.

ISO 8601 Date

^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$

Validates YYYY-MM-DD. Does not validate calendar correctness (Feb 30 passes) β€” add that check in code.

Hex Color

^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$

Matches #fff and #ffffff. Extend with {8} to support 8-digit RGBA hex.

IPv4 Address

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

Validates each octet is 0–255.

Extract HTML Tags

<([a-z][a-z0-9]*)(?:\s[^>]*)?>[\s\S]*?<\/\1>

Useful for stripping or extracting HTML in text processing. Do not use this to parse real HTML β€” use a DOM parser.

Slug (URL-safe)

^[a-z0-9]+(?:-[a-z0-9]+)*$

Validates kebab-case URL slugs. All lowercase, no leading/trailing hyphens, no consecutive hyphens.

Tips for Safer Regex

  1. Test with adversarial input β€” try empty strings, very long strings, and special characters.
  2. Avoid nested quantifiers like (a+)+ which cause catastrophic backtracking.
  3. Use verbose mode when available to add comments to complex patterns.
  4. Compile once, use many times β€” compiled regex objects are reusable and significantly faster.