Find the matching closing bracket in a long string
A bracket-matching helper that ignores brackets inside quotes. The regex finds
the candidates, the scan keeps a counter, and the function returns the index
of the matching close.
import re
PAIRS = {"(": ")", "[": "]", "{": "}"}
def match_index(text: str, start: int) -> int:
opening = text[start]
closing = PAIRS[opening]
depth = 0
in_string = None
escape = False
for index in range(start, len(text)):
char = text[index]
if escape:
escape = False
continue
if char == "\\":
escape = True
continue
if in_string:
if char == in_string:
in_string = None
continue
if char in "\"'":
in_string = char
continue
if char == opening:
depth += 1
elif char == closing:
depth -= 1
if depth == 0:
return index
return -1
The escape flag is what keeps a quoted backslash from ending the string early.