My regex for nested brackets keeps failing

Back to list2026-08-22
You

My regex for nested brackets keeps failing.

ChatGPT

Because regular expressions cannot count. Nesting needs a parser, even a ten line one with a stack. The regex that appears to work handles two levels and fails on the third, which is worse than not working at all.

You

My pattern swallows the whole line.

ChatGPT

.* is greedy: it takes everything, then backtracks. Use .*? for the shortest match, or better, a negated class like [^"]* which cannot cross the delimiter at all and does not backtrack.