Alex Costantino

Information Technology DevelopmentI.T. Development

🇬🇷️ 🇮🇹 EN

Regular Expressions: the dark magic of parsing




Regular Expressions: the “dark magic” of parsing.

That sounds impressive, doesn’t it?

In reality, they can sometimes feel less like dark magic and more like a mysterious spell that works perfectly, until one oddly specific string brings everything down.

Okay, I may be exaggerating a little. Let me explain how I reached that conclusion.

The Beginning

As you may already know, I’m the creator of StyleZero.

StyleZero has its own parser, which was originally built using custom matching logic, without relying on regular expressions.

At some point, I came across a Facebook post from an experienced developer who said that regex had saved him many hours of work.

Naturally, I thought:

Why not? Let’s see what happens.

The Implementation

Writing one enormous regular expression for the entire StyleZero parser was clearly not going to end well, so I divided the logic into several variables.

The final result was not exactly easy reading, but it worked.

To make a long story short, I managed to replace logic that had previously been spread across several files with a single function.

It looked fantastic.

Everything worked perfectly, until, one day, it didn’t.

Classic.

So, What Happened?

A colleague who had become a big fan of StyleZero noticed that certain SVGs caused the compiler to stop working.

It was not a disaster, since he had already found a workaround. Still, after reproducing the same problem in a few other cases, I wanted to understand what was actually going wrong.

After several tests and a lot of carefully removing parts of the template, I discovered that StyleZero would break whenever it encountered an alphanumeric string between 13 and 16 characters long.

At first, I found this rather funny.

On the one hand, the parser could process enormous templates without any trouble. On the other hand, a tiny file containing something like this could bring it down:

234n905ct395945

After some investigation, I confirmed that the regular expressions were responsible.

I then spent three or four very focused days rewriting the parser from scratch so that version 9.2.1 could be released.

In the end, the problem turned into a useful opportunity. The new parser is significantly better than the previous one, both structurally and functionally.

My Advice

Regular expressions are powerful, so use them, but use them thoughtfully.

They are excellent for small, clearly defined matching tasks. When the logic starts becoming large, complex, and difficult to explain, a more maintainable solution may save you from a few surprising adventures later.