Common Regular Expressions

24th March 2008

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.

IP Address

(((\d{1,2}|(1\d{2})|(2[0-4]\d)|25[0-5]))\.){3}((\d{1,2}|(1\d{2})|(2[0-4]\d)|25[0-5]))

This also checks to see that the IP address is within the range 0.0.0.0 to 255.255.255.255.

Email Address

([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))

Complete URLs

https?://(\w*:\w*@)?[-\w.]+(:\d+)?(/([\w/_.]*(\?\S+)?)?)?

This will match virtually any URL.

HTML Comments

<!---{2,}.*?-{2,}-->

Inline Code Comments

//.*

This will match inline comments in C, PHP, Java, JavaScript etc.

Add new comment

The content of this field is kept private and will not be shown publicly.