# Are JS regexes really not able to parse HTML?

Many people have seen this fantastic meme answer before about how we should use a parser to parse HTML instead of using Regex. The argument is that HTML is not regular and thus cannot be parsed using Regex.

However, a closer look at JS regexes, it seems JS regexes can indeed describe irregular languages via backreferences. Languages such as $a^n|a^n\ \{\ a \in \Sigma, n \in N\ \}$ can be described with:

/(.+)\|\1/


The regexes JS has are really "enhanced regular expressions", but I'm not sure if that's enough to parse HTML which is obviously irregular. I'm also not sure if they at least cover every CFG languages.

• You are misunderstanding that answer. I don't read that answer as an attempt to discuss what is possible; rather, I read it as an attempt to describe what is desirable / a good idea. About regexps vs regular languages, please see cs.stackexchange.com/q/4839/755 and cs.stackexchange.com/q/24031/755. Is there a more precise technical question you can ask that doesn't require knowledge of the entire set of constructs that can appear in JS regexes? – D.W. Sep 16 '17 at 0:10
• @D.W. A more technical version would be, if we add the ability of backreferences to classical regular expressions, will we be able to describe CFG languages. The second link in your comment seems to suggest that it's not just possible, but in fact it is NP-Complete. Is there any example that can help me understand why (ex how do you represent $a^nb^n$ with regular expression with backreferences added?) – Derek 朕會功夫 Sep 16 '17 at 0:16
• That more technical version is already answered at the links I gave you. If you want an example, that's a different question entirely and should probably be posted separately. – D.W. Sep 16 '17 at 0:17
• Some regexp flavors are Turing-complete, if I recall, so the answer may depend on the nitty-gritty of what exactly JS regexps can do. Meh. – Raphael Sep 16 '17 at 7:05
• JS regexps might be able to recognize the HTML language, but afaik they don't provide any mechanism to extract a parse tree (or derivation, if you prefer) so I don't see how you could claim that you can parse HTML with a JS regexp. Obviously, regexps could be a useful tool for an HTML parser -- to tokenise the input, for example -- bit I don't think that's what you're asking. The referenced question correctly suggests that parsing HTML is harder than it looks, and practical programming advice can only be "use an existing library". – rici Sep 16 '17 at 17:51