Hone

Lessons · Regex · a pattern cannot count brackets

It can find them; it cannot pair them

A regular expression has no memory of how deep it currently is, so it cannot match balanced brackets to any depth.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Every hand-written pattern for a nested format encodes one fixed depth. It passes on the example and fails on the real data, which is the worst possible order.

How to think about it

If the format nests -- JSON, HTML, source code, arithmetic -- a parser is not the heavyweight option, it is the only correct one.

Worked example

re.findall(r'\(', '((a))')
It counted the opening brackets.
re.findall(r'\((.*?)\)', '((a))')
And here is it pairing them wrongly: the lazy match stops at the first close.

Your turn

Find every opening bracket.

re.findall(r'', '((a))')

The trap

Some engines add recursion as an extension. Python's re does not, and a pattern that relies on one is not portable to it.

Practise a pattern cannot count brackets on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.