Skip to content

fix: use greedy matching in FINAL pattern to handle nested parentheses#75

Merged
alexzhang13 merged 2 commits intoalexzhang13:mainfrom
yahocan:main
Jan 29, 2026
Merged

fix: use greedy matching in FINAL pattern to handle nested parentheses#75
alexzhang13 merged 2 commits intoalexzhang13:mainfrom
yahocan:main

Conversation

@yahocan
Copy link
Contributor

@yahocan yahocan commented Jan 28, 2026

Summary

Fixes a bug in find_final_answer() where non-greedy regex matching would incorrectly stop at the first closing parenthesis, breaking FINAL() patterns with nested parentheses.

Problem

The old pattern ^\s*FINAL\((.*?)\) used non-greedy matching (.*?), which matched to the first ) instead of the last ). This caused incorrect parsing for:

  • Function calls: FINAL(func(arg1, arg2)) → captured func(arg1, arg2 (missing closing parenthesis)
  • Tuples/lists: FINAL([1, 2, 3], (4, 5)) → captured [1, 2, 3], (4, 5 (missing closing parenthesis)
  • Nested expressions: FINAL(calculate(10, 20) + process(data)) → only captured calculate(10, 20

Solution

Changed regex pattern from ^\s*FINAL\((.*?)\) to ^\s*FINAL\((.*)\)\s*$:

  • Greedy (.*) matches to the last closing parenthesis
  • Added \s*$ anchor to ensure pattern matches to end of line

Testing

Added comprehensive test test_final_with_nested_parentheses_greedy_matching() covering:

  • Function calls with nested parentheses
  • Lists and tuples with multiple closing parentheses
  • Complex nested dictionaries
  • Multiple function calls in expressions

All 135 existing tests pass.

Files Changed

  • rlm/utils/parsing.py: Updated FINAL regex pattern (2 lines modified)
  • tests/test_parsing.py: Added nested parentheses test (27 lines added)

@alexzhang13
Copy link
Owner

Hm I see, yeah this is a good idea. There are some weird potential cases (e.g. FINAL(a) then FINAL(b)) but I don't think this should even happen in the first place.

@alexzhang13 alexzhang13 merged commit 3a63ff4 into alexzhang13:main Jan 29, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments