Any programmer worth their salt should have a few tricks up their sleeve. Among these should be regular expressions. The syntax for RegEx is unusual and hard to get used to, but only with a little practice (or even a cheat sheet) you can realize the full potential when it comes to text processing and string handling.
Pretty much every modern programming language provides a library necessary to use regular expressions. For reference: C++ / Boost, Java, .NET (C# and VB), Perl, Python, PHP, and more. Further more, popular IDEs and Text Editors usually support Find/Replace using RegEx patterns which can greatly increase productivity.
Through the years I have seen RegExes that match things from the simple, to the bizarre. So I decided to put together a list of commonly used ones as a reference for myself (and others):
- HTML Hex Value
- E-Mail Address
- Phone Number
- IP Address
- Host Names
- White Space
- Credit Cards
1. HTML Hex Color Values (Of length 3 or 6)
As you can see, this pattern first matches the literal ‘#’ followed by exactly 3 or 6 valid hex digits (a-f, 0-9). This pattern should probably be used sparingly since there are many other methods for getting color input from the user. Though, this may be used to validate the input after they have made their selection.
2. Valid URLs
This pattern will match common URLs that begin with http, https, or neither. Note that it does not match ftp. It then checks to make sure only valid characters exist in the domain and path (which is optional so that it will match top level domains and things such as localhost). Also note that directories can optionally end with a slash.
3. E-Mail Addresses
By now you should recognize this pattern. The only tough part about constructing it is figuring out which characters are valid for e-mail addresses (which has been done for you). It will match common e-mails such as firstname.lastname@example.org. Note that the user name may also contain underscores in addition to alphanumerics.
4. Phone Numbers
This pattern matches simple, 7 digit US telephone numbers.Â Note that the number must be hyphen seperated and the first digit must be between 2 and 9 for it to be valid.
Edit: Steven Levithan has an excellent write-up on this subject that covers far more, including International phone numbers.
5. IP Address
This is the simplest solution. It will match anyÂ IPv4 addressÂ in the range from 0.0.0.0 to 999.999.999.999. Any octet values greater than 255 are invalid, so you may consider using this for IPv4 matching instead:
This matches similar values to the one above but restricts it to values from 0.0.0.0 to 255.255.255.255.
For most cases, this regexÂ can lead to code smells. You should peruse your programming language documentation for something similar to IPAddress.TryParse() found in the .NETÂ framework before resorting to this method for validation.
6. Host Names
This pattern matches exactly to the specification defined in the IETF RFC for hostnames and will match any valid hostname that you feed it. Note that modern hostnames are valid if they begin with a digit (even though the RFC does not specify this).
Note that minor changes can increase the power of this regex:Â ^[ s]+ will find whitespace at the beginning of a line, [Â s]+$ will find whitespace at the end of a line, or you may combine these together. Also, you can substitute by changing s which matches returns, newlines, tabs for r, n, and t respectively or remove the leading space to not include spaces.
Another one useful for programmers in RegEx enables search/replace functionality. These RegExes are very useful if you want to automate the removal of dead or commented out code. Just open your favorite IDE, select Find -> Replace, enable regexes,a nd search for the given patternÂ to quickly remove the unnecessary clutter.
Different languages use different syntax for comments, so I’m going to try and list as many as I can think of off the top of my head:
ThisÂ pattern matches all single line comments that begin with the pound sign (#). Useful for Perl and RubyÂ programmers.
This one is a stronger version of the one above adapted to match compiler directives and pragmas in C / C++ source code.
This pattern matches multiline comments in the form of /* Comment goes here */. This style is common in many programming languages such as C++ and Java.
This one matches doubleslash style comments such as // Comment goes here. Note that it will match the entire line if the string // is found. This is another very common style for comments.
Finally, this pattern matches VB style comments which begin with an apostrophe.
9. Credit Cards
Matches a valid Visa credit card, both new and old style since the newer cards have a few extra digits. Visa cards must begin with 4.
Matches a valid MasterCard number. MasterCard must begin with 5.
Matches a valid Amex card (must begin with a 3).
Note that before using these, it would be best to strip white-space and hyphens (or even better, all non-digits). These would be useful for validation on a web app for an online store.
^(19|20)dd[- /.](0[1-9]|1)[- /.](0[1-9]|[0-9]|3)$
This matches dates in the format of yyyy-mm-dd. This enforces hyphen delimiters and also checks that the date is within a valid range. Most programming languages have a rich syntax for dates and date/time validation. You should probably check documentation for it before resorting to using a regex.Â Also you couldÂ check our jQuery if you are building a web app or website.