Regex Rules & Examples

Here is a collection of commonly used regular expressions for various tasks. You can use these examples to learn how to write your own regex or to copy and paste them into your projects.

Usernames and Passwords

Username (alphanumeric, 3-16 characters): /^[a-zA-Z0-9]{3,16}$/

Username (alphanumeric, with underscores and hyphens): /^[a-zA-Z0-9_-]{3,16}$/

Password (at least 8 characters, one uppercase, one lowercase, one number): /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/

Password (at least 8 characters, one uppercase, one lowercase, one number, one special character): /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/

Numbers

Integer: /^-?\d+$/

Positive Integer: /^\d+$/

Negative Integer: /^-\d+$/

Floating-Point Number: /^-?\d*\.\d+$/

Positive Floating-Point Number: /^\d*\.\d+$/

Hexadecimal Number: /^[0-9a-fA-F]+$/

Dates and Times

Date (YYYY-MM-DD): /^\d{4}-\d{2}-\d{2}$/

Date (MM/DD/YYYY): /^(0[1-9]|1[0-2])\/(0[1-9]|[12][0-9]|3[01])\/\d{4}$/

Time (HH:MM): /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/

Time (HH:MM:SS): /^([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/

Web

Email: /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/

URL: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

URL with query string: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?(\?.*)?$/

HTML Tag: /<([a-z][a-z0-9]*)\b[^>]*>.*?<\/\1>/

Miscellaneous

Phone Number (North American): /^(\+?1\s?)?(\(?\d{3}\)?[\s.-]?)?\d{3}[\s.-]?\d{4}$/

Credit Card (Visa, Mastercard, American Express): /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})$/

IP Address (IPv4): /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

IP Address (IPv6): /(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/

Share this page