The power of Regular Expressions, Find and Replace

Such is the power of regular expressions combined with find and replace means that with a simple statement like this <img?.{1,999}?> will locate every image in your HTML code in site wide search. It’s also the quickest and easiest way for a web designer to destroy a web site so back up and double check before you get stuck in.

screen shot showing find and replace pop up window

Regular expressions enhance standard find and replace

For a recent assignment this is exactly what I needed to do. Working with an archive of over 200 HTML pages from an old news section that needed the copyright expired images removing. The pages had all been hard coded with no template in sight.

Daunted by the thought of opening each page and manually locating and removing each image I put my mind to finding a quicker way.

I considered a handful of bespoke advanced find and replaced applications that promised to quickly solve my problem and if money was no object I may well have gone down this root. At the back of my mind though was the nagging thought that the correct way to approach this is to learn some regular expression.

So I ended up with <img?.{1,999}?> but what does this mean? The breakdown (when used with Dreamweaver) works like this:

  • <img locks on to the start of the image tage
  • ? is a ‘Quantifier’ meaning it will match no more than once
  • .matches any single character, except a newline
  • {1,999} match at least once, but no more than 999 times
  • > locks on to the end of the image tag

So there you have it. Use the above regular expression to find and replace with nothing to remove all images from your source code in one move.

This entry was posted in code, HTML and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *