HeadlinesBriefing favicon HeadlinesBriefing.com

The True Power of Modern Regular Expressions

Hacker News •
×

A common refrain on Stack Overflow is that you cannot parse HTML with regular expressions because HTML is not a regular language. However, this distinction between formal language theory and practical programming is often misunderstood. In formal theory, a regular grammar is defined by specific production rules, such as those used to define natural numbers.

While formal regular expressions are limited to Type 3 languages in the Chomsky hierarchy, modern implementations like PCRE are far more capable. Programmers use regex derivatives that can actually match context-free languages. For example, using recursive subpatterns, a regex can match the language {a^n b^n}, proving it can handle non-regular patterns.

This increased power means that modern regex engines can navigate complex structures. While programming languages like PHP rely on context-free grammars to define their syntax, the ability of modern regex to handle recursion allows it to tackle tasks much closer to formal parsing than previously thought.