Regex Love

Regex is such a great tool. You can do powerful things with tiny bits of code.

For example, what if you wanted to validate user input of archeological site Trinomials.  A Trinomial is made up of a number designating the US State (Texas is the 41st state), followed by a 2 letter county abbreviation, and finally the archeological site number within that county.  A Trinomial for Brewster  County, Texas should look like:

41BR1301

Suppose that you also want to restrict the user to only entering the number designating Texas in the Trinomial. Also, suppose you want all county letters to be capitalized. You could write a longer bit of PHP or some other type of code to validate this, but a Regex does the whole thing with just a few characters:

^(41)[A-Z]+[0-9]+$

 

Here is a Regex to validate about 99% of email addresses:

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

 

Here is a Regex to validate time of day entries (examples: 9:45pm, 10:00am).

^(((0?[1-9]|1[012])(:[0-5][0-9])?am)|((0?[0-9]|1[012])(:[0-5][0-9])?pm))\b$

 

There is so much you can do with Regex. You can trim white space and line end characters from large amounts of text or change the names or extensions of hundreds of files or scour and remove non-printing characters from text. You can use it to match dates and floating point numbers. The list is endless.