List of the Most Common Regular Expressions
This tutorial will show you some of the most common regular expressions you can use in your web applications.
What Are Regular Expressions?
Regular Expressions, or regex
for short, are patterns defined to compare against user input or other text strings. They're beneficial in cases where you need to validate some type of user input, including email addresses, phone numbers, ZIP codes, and more.
Most Common Regular Expressions
Here is a quick list of some of the most common regular expressions you can use throughout your web applications:
Email Address
This regex will match against any valid email address:
/(([0-9a-zA-Z\.\-\_]+(\.[0-9a-zA-Z\.\-\_]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
URL
This regex will match against any valid URL, allowing for both "http" and "https" protocols, and optional "www.":
/http[s]?\:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/
Phone Number
This regex will match against a 7- or 10-digit phone number:
/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4}$/
ZIP Code
This regex will match against a 5-digit ZIP code, or a 9-digit ZIP code containing both the main ZIP code and optional ZIP+4 with a hyphen:
/[0-9]{5}(\-[0-9]{4})?$/
Conclusion
That's the rundown of the most common regular expressions.
I created a tutorial to validate user input with regular expressions if you're using JavaScript.
If you have any you would like to see added that would help others, let me know in the comments below.
Created: July 20, 2022