Extract a boxed answer from a math benchmark response. Math competition and benchmark answers are often formatted as \boxed{answer}. Parse and extract the content inside the last \boxed{} command from a LaTeX-formatted string.
def extract_boxed_answer(text: str) -> str:
idx = text.rfind("\\boxed{")
if idx == -1:
return ""
start = idx + len("\\boxed{")
depth = 1
i = start
while i < len(text) and depth > 0:
if text[i] == '{':
depth += 1
elif text[i] == '}':
depth -= 1
i += 1
if depth != 0:
return ""
return text[start:i - 1].strip()\boxed{ in the text using rfind, since the final boxed expression typically holds the answer.{ and decrement on }.