If you use regular expressions on a, ehm, regular basis then you might be familiar with the fact that it typically  results in code that has a short h

A better regex experience by eval

submited by
Style Pass
2024-06-07 08:30:18

If you use regular expressions on a, ehm, regular basis then you might be familiar with the fact that it typically results in code that has a short half-life in terms of understandability. Yes, that carefully crafted string that was the result of numerous trials and errors and that, after tuning the greediness of one group with the right amount of laziness of the following groups, finally delivered the right result. Chances are that that exact thing will look totally opaque in, give or take, a week or two (probably less for your team mates 😬).

Definitely the best way to make your regular expressions easier on the eyes is to insert comments. And this can be simply done by switching on the comment-flag, supported by most regex engines: (?x). Say, we need a regex to match a simple URL like "https://google.com/search#fragment", then the difference might be something like this:

The comment-flag instructs the regex engine to ignore any whitespace (i.e. trailing, leading and in between!), newlines, as well as anything following a #. And so we have numerous options to make it clearer what's going on where by spreading the various groups out over multiple lines, use indentation and add comments.

Leave a Comment