Fix trailing named group replacement in simplify_regexp

Previously, the final named group was not replaced if the pattern lacked a trailing '/'. This ensures all named groups, including the last one, are properly replaced.

Fixes #6888.
This commit is contained in:
utkarsh.arya@zomato.com 2025-11-15 23:00:50 +00:00
parent 0545781764
commit a1eed87a13
2 changed files with 10 additions and 6 deletions

View file

@ -167,12 +167,6 @@ def replace_named_groups(pattern):
# Handle nested parentheses, e.g. '^(?P<a>(x|y))/b'.
unmatched_open_brackets, prev_char = 1, None
for idx, val in enumerate(pattern[end:]):
# If brackets are balanced, the end of the string for the current
# named capture group pattern has been reached.
if unmatched_open_brackets == 0:
group_pattern_and_name.append((pattern[start:end + idx], group_name))
break
# Check for unescaped `(` and `)`. They mark the start and end of a
# nested group.
if val == '(' and prev_char != '\\':
@ -181,6 +175,12 @@ def replace_named_groups(pattern):
unmatched_open_brackets -= 1
prev_char = val
# If brackets are balanced, the end of the string for the current
# named capture group pattern has been reached.
if unmatched_open_brackets == 0:
group_pattern_and_name.append((pattern[start:end + idx + 1], group_name))
break
# Replace the string for named capture groups with their group names.
for group_pattern, group_name in group_pattern_and_name:
pattern = pattern.replace(group_pattern, group_name)

View file

@ -354,6 +354,10 @@ class AdminDocViewFunctionsTests(SimpleTestCase):
(r'^(?P<a>(x|y))/b/(?P<c>\w+)ab', '/<a>/b/<c>ab'),
(r'^(?P<a>(x|y)(\(|\)))/b/(?P<c>\w+)ab', '/<a>/b/<c>ab'),
(r'^a/?$', '/a/'),
# Regression tests for #XXXXX: named groups at the end should be replaced.
(r'entries/(?P<pk>[^/.]+)/relationships/(?P<related_field>\w+)', '/entries/<pk>/relationships/<related_field>'),
(r'test/(?P<id>\d+)', '/test/<id>'),
(r'^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>(foo|bar)\w+)$', '/<sport_slug>/athletes/<athlete_slug>'),
)
for pattern, output in tests:
with self.subTest(pattern=pattern):