Regex of the day: Optional HTML tags
It’s one of those regex-laden days, and I’m really starting to grok more complicated expressions:
^(?:\s+|)<(\w+)(?:\s+|)((?:.*?|))>(.*?)(?:<\/(.*?)>|)(?:\s+|)$
This expression parses a line that contains HTML tags based on the following logic, expecting that:
- There will be a start tag near the beginning of the line, possibly padded on the left with spaces that are ignored
- The opening tag may contain some HTML parameters
- There may be a closing tag on the line
- There may be spaces on the right of the closing tag that will be ignored
The expression will parse the following example into 4 parts:
<h1 id="test">This is a test</h1>
- h1
- id=”test”
- This is a test
- h1
Learning regex to the point of being able to write complex expressions has taken a couple of years, but has been well worth the effort. To define the same parsing logic in C or C++ (using standard mechanisms) would take 20-30 minutes, and would occupy a page of code. You just have to remember that a regex is a small script, and that it should be tested (and documented) like one.
Regex is like a lot of little languages too (like SQL, bash, m4). It’s terribly useful, succinct, and worth having in your toolkit. It’s not something to hide in layers of abstraction either, rather it’s something that deserves use alongside your ‘real’ tools. I find that developers are in the habit of hiding (or hiding from) little languages, something that results in the too-many-elbows syndrome: insulating yourself from the real power of your tools, making things more complicated in the process.
Simple, in the end, is in the knowledge of the beholder. If you understand regex, code that contains it can be simpler.

RSS![2 comments [Comment]](/images/comment.png)
