Regular Expressions

Useful regular expressions

Regular Expression To Find Single Apersands In Text

22nd September 2008 - 1 minute read time

Encoding special characters in a block of HTML or other code can be a pain because there might already be ampersands there that impart encoding. This might be an ampersand that has already been encoded with a &, or it might be an ampersand in the code as an if statement or similar.

Use the following regular expression to find any ampersand that hasn't already been encoded.

([^&])&(?!#?[a-zA-Z0-9]{2,6};|\$|&)

When using replace, you can turn any ampersand into & by using the following replace.

$1&

The only problem with this statement is when the code uses a & operator as part of a statement to do bitwise operations.

Common Regular Expressions

24th March 2008 - 1 minute read time

Here are some of the regular expressions that I frequently use.

Find a blank line

^$

Spaces

[ \t]+

You can use this to break a text string apart into words.

Date

\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}

This will match anything in the format mm/dd/yyyy, or even dd/mm/yyyy.

[A-Z][a-z][a-z] [0-9][0-9]*, [0-9]{4}

Will match a formatted date, such as Mar 24, 2007.

Time

([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?

This will match HH:MM or HH:MM:SS or HH:MM:SS.mmm.

RegExLib.com: The Regular Expression Library

22nd March 2008 - 2 minutes read time

Writing regular expressions can sometimes be a real pain, especially if you are not used to them. Rather than trying for yourself to make a regular expression you might want to think about looking for regular expressions that other people have made. Rather than reinventing the wheel to prove you can do something,using free third party regular expressions can save you a lot of time.

The RegExLib or regular expression library is a great resource for finding any regular expression that you are looking for.

RegExLib.com: The Regular Expression Library

reWork: A Regular Expression Workbench

21st March 2008 - 2 minutes read time

Regular expressions are a very useful tool for any programmer wanting to validate input, format strings, change words, reformat data or even split apart a string into an array. However, when you are starting out, writing them it can be hard going, they are not very easy to learn and the only way to really understand them is to practice, practice, practice.

This is where reWork steps in. It is a fully functional online regular expression workbench that will allow you to plug the expression and the text in one end, and it will show you exactly what is being matched. This simple JavaScript program is far better than any stand alone application I have seen and has more functionality than you could even think about.

reWork: Regular Expression Workbench