[TIPS] Widely-used REGEX
By hientd, at: 2023年8月2日14:22
Useful Regex Patterns
If you've ever found yourself needing to validate an email address, extract numbers from a string, or ensure a password meets specific criteria, then you know the power of regular expressions (regex). They might seem intimidating at first, but once you get the hang of them, they're incredibly handy.
In this post, I've gathered some of the most common and useful regex patterns that I frequently use in my projects. Whether you're a seasoned developer or just starting out, these patterns will save you time and make your coding life easier
Email Validation
Matches an email address. It starts with alphanumeric characters (including .
, _
, %
, +
, -
), followed by an @
symbol, a domain name, a dot, and a top-level domain (at least two letters).
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Phone Number Validation (US)
Matches US phone numbers with optional country code. It handles formats like +1 (123) 456-7890
, (123) 456-7890
, 123-456-7890
, etc.
^(\+\d{1,2}\s?)?(\(\d{3}\)|\d{3})[-.\s]?\d{3}[-.\s]?\d{4}$
URL Validation
Matches HTTP/HTTPS URLs with optional www
. It supports domain names with subdomains and optional trailing slash.
^https?:\/\/(www\.)?[a-zA-Z0-9-]+(\.[a-zA-Z]{2,})+\/?$
Date Validation (YYYY-MM-DD)
Matches dates in the format YYYY-MM-DD
, ensuring valid month (01-12) and day (01-31) values.
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$
Postal Code Validation (US)
Matches US ZIP codes in the format 12345
or 12345-6789
.
^\d{5}(-\d{4})?$
IPv4 Address Validation
Matches IPv4 addresses, allowing values from 0.0.0.0
to 255.255.255.255
.
^(\d{1,3}\.){3}\d{1,3}$
Hex Color Code
Matches hex color codes with or without #
, in 3 or 6 digit formats.
^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$
Username Validation
Matches usernames 3 to 16 characters long, containing letters, numbers, dots, underscores, and hyphens.
^[a-zA-Z0-9._-]{3,16}$
Password Validation
Matches passwords with at least one lowercase letter, one uppercase letter, one digit, one special character, and at least 8 characters long.
(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}
Whitespace Trimming
Matches leading or trailing whitespace in a string, useful for trimming spaces from input data.
^\s+|\s+$