When not to use a regex
HTML, JSON and nested expressions defeat regex for different reasons. See concrete failures, then the alternative, a regex tokenizer plus a small parser.
Regular languages and linear-time enginesBackreferencesQuoted strings and CSV fieldsParsing log lines with named groups
When not to use a regex
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Regex fails on nested structure because its memory is finite: HTML and expressions with arbitrary nesting need a stack, and a parser has one.
- My regex link extractor on a small HTML page missed a real link (an attribute containing >) and returned two links from a comment and a script. Python's html.parser returned exactly the two real ones.
- Extracting a JSON key by regex returned a nested name instead of the top-level one. JSON.parse is shorter and correct.
- A good split is regex for tokens, a parser for structure. A tokenizer plus recursive-descent parser of about ten dense lines evaluated nested expressions and rejected unbalanced ones. It hit a stack limit at depth 20,000, which a counter loop does not.
- The test for a clever regex is who maintains it. If it needs a comment longer than itself, or a test table to trust, reach for a parser or a library.
The pattern you keep writing, and its ceiling
You have a hammer and the next thing looks like a nail. Pull the links from this HTML, grab one field from this JSON, check these brackets. All three are text, and regex is for text. The reason they go wrong is not that regex is weak. It is that these inputs have structure that nests, and the previous lessons showed that a regex has a fixed amount of memory. It can recognise a flat pattern and cannot count nesting depth.
I’ll give concrete failures first, then what to use instead.
HTML
I wrote a small page with a link, a commented-out link, a link whose title contains >, a script that mentions a link in a string, and nested divs. Then I extracted links with the obvious pattern <a\s+[^>]*?href="([^"]*)":
regex hrefs: ["/x", "/commented-out", "/in-script"]
html.parser (Python): ['/x', '/y']
The regex returned two things that are not links, the comment and the script string, and it missed /y because [^>]* stopped at the > inside title="1 > 0". Python’s html.parser handled comments, script text and quoted attributes correctly and returned the two real links.
Nesting is worse. For <div class="inner"><div>deep</div>after</div>:
lazy (.*?)</div> → "<div>deep"
greedy (.*)</div> → "<div>deep</div>after</div>"
The lazy version stops at the first closing tag, which belongs to the inner div. The greedy version runs past the right one to the last </div> in the document. Neither returns <div>deep</div>after. Counting the pairs requires a stack. The lesson on regular languages showed that a pattern limited to depth d fails at depth d+1.
Regex is fine for a quick one-off on HTML you control and have looked at. It is wrong for HTML you do not control, or for anything that must keep working.
JSON
I took {"note": "he said \"name\": \"fake\"", "user": {"name": "inner"}, "name": "real"} and pulled name with "name":\s*"([^"]*)". It returned inner, the nested one, as its first hit, and ["inner", "real"] for all hits. JSON.parse(j).name returned real and .user.name returned inner. The regex doesn’t know what depth a key is at. JSON.parse is one call, handles escapes and rejects malformed input. If you only need to scan a huge file, use a streaming JSON parser rather than a pattern.
Expressions and nesting
Balanced parentheses defeat a regex for every depth. Here is the alternative I built: a regex for the tokens, plus a small recursive-descent parser for the structure.
const re = /\s*(?:(\d+(?:\.\d+)?)|(.))/y; // a number, or any single character
That sticky regex does the flat work, splitting 2*(3+4)-5 into numbers and symbols. Three functions, expr, term and factor, handle precedence and parentheses by calling each other. About ten dense lines in all. Results:
2*(3+4)-5 9
((1+2)*(3+4))/7 3
-(2+3)*2 -10
1+(2*3 error: missing )
2*(3+4)) error: trailing )
The nested cases evaluated correctly and the two broken inputs were rejected with a message that says what was wrong, which a regex cannot give you. A depth of 2,000 parentheses worked. Depth 20,000 threw RangeError: Maximum call stack size exceeded, so parsers have limits too. For only checking brackets, a counter loop handled a million levels: balanced("(".repeat(1e6) + ")".repeat(1e6)) was true, and (() and ())( were false. For real grammars, cap the depth or use an explicit stack.
The cost of a clever regex
A regex that works is not the end of the story. The code base keeps it for years. The depth-limited paren pattern was 92 characters at depth 10 and the HTML standard’s email pattern is 136 characters long (I measured it with source.length), and both are write-once code. Ask who will change it, how they will know it still works, and what it does on input you did not imagine. If the honest answers are “someone who has never seen it”, “they won’t” and “it might hang”, write a parser, call a library, or at minimum put the regex in a test table (the last lesson shows how).
A rule of thumb that has worked here:
- Flat, local, one-line shape: regex.
- Nesting, quoting, escaping across lines, or a published grammar (HTML, JSON, CSV files, URLs): the platform parser or a library. The theory behind this split is in lexing and parsing.
- A grammar of your own: tokenize with regex, parse with code.
About the video
“RegEx Tutorial - A Tutorial on Regular Expressions and HTML Parsing” by Fullstack Academy was published 11 November 2016 and runs 13 minutes 21 seconds. The description says it explains JavaScript’s regex implementation and its limits, and why regex may not suit parsing arbitrary HTML. The chapters include “The Chomsky hierarchy”, “Regex in JavaScript”, “Regex object pitfalls” and “Parsing HTML with regex”. I clipped from the Chomsky hierarchy chapter to the end. I couldn’t read a transcript, so I can’t confirm what it concludes, and it does not cover JSON, tokenizers or the cost of maintenance. It is nearly ten years old, so any JavaScript syntax it shows predates features like named groups. English per its title and description.
What I did not run
Browsers’ DOM parsers (DOMParser is not in Node), jq or streaming JSON tools, parser generators, and PCRE recursion on HTML. The HTML page and JSON string are small samples I wrote, not a survey of real pages.
Next
If you decide a regex is the right tool after all, the last lesson is about living with it: reading, testing and maintaining a regex.
Check yourself
Why can't a regex match properly nested HTML tags?
Matching nested tags means remembering how many are open, to any depth, and a pure regex has fixed memory. A lazy pattern stops at the first closing tag, and a greedy one runs to the last, and both get nested content wrong. A parser keeps a stack.
In what two ways does a regex link extractor go wrong on real HTML?
It matches inside comments and script strings, which are not links, and it can stop early at a > inside an attribute value. In my test it returned the commented-out and in-script links and missed a real one.
What can you use a regex for when you are writing a parser?
Tokenizing: splitting the input into numbers, operators and names. Regex is good at the flat, local part, and the parser handles structure. My tokenizer was one sticky regex, and the parser was a few mutually recursive functions.
A recursive-descent parser failed at nesting depth 20,000 with a stack error. What does that tell you about the alternatives?
Parsers have their own limits too. Deep input can exhaust the call stack, so for pure bracket matching a counter loop is better, and for real grammars you can use an explicit stack or cap the allowed depth.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.