How to replace HTML tags using regular expressions

3 Nov 2011

Strictly speaking, you cannot parse HTML using only regular expressions. The reason is explained in any computer science curriculum: HTML is a context-free language, but regular expressions allow only regular languages. So, you cannot match nested tags with them.

However, regexes are really useful for quick search and replace in your web pages. Full parsing is unnecessary, because you know the HTML code that you wrote. Approaches that are “impure” from theoretical point of view work extremely well in this setting. You even can simplify the regexes shown below: say, if you never insert newlines between a and href, then you need not to allow for them in your regular expression.

Match an HTML tag


This regex matches an <a> tag with any attributes. If you break it into parts:

Parenthesis are used to capture the attributes and the text inside tag. You can then refer to them using \1 and \2 in the replacement. For example, you can remove all links:

Search for <a\s(.*?)>(.*?)</a> and replace with \2

As mentioned above, the regex will not correctly match nested <a> tags; it just finds the next closing tag of the same type. But in this case, it's not important, because the nested <a> tags make little sense :)

Match an opening HTML tag with some attribute


This regex matches an opening <a> tag with href attribute. The differences from the previous example are:

This regex is simple enough and works in most cases. The HTML standard allows spaces around = and single quotes instead of double quotes in attribute values. If you need to match such tags, you need a more complicated regex:


But simpler regexes usually suffice. Here is how you can replace absolute links with relative ones:

Search for <a\s([^>]*\s)?href="*?)" and replace with <a \1 href="\2"

I hope that this short tutorial convinced you of the power of regular expressions :)

See also: Regular expression reference

Aba Search and Replace screenshot

Replacing text in several files used to be a tedious and error-prone task. Aba Search and Replace solves the problem, allowing you to correct errors on your web pages, replace banners and copyright notices, change method names, and perform other text-processing tasks.

This is a blog about Aba Search and Replace, a tool for replacing text in multiple files.