1
0
mirror of https://github.com/django/django.git synced 2024-12-23 01:25:58 +00:00

Refs #32499 -- Fixed escaped metacharacters in simplify_regex().

This commit is contained in:
Nick Pope 2021-07-07 23:26:06 +01:00 committed by Mariusz Felisiak
parent 9f7809ece3
commit 85540da930
2 changed files with 33 additions and 1 deletions

View File

@ -144,7 +144,11 @@ unnamed_group_matcher = _lazy_re_compile(r'\(')
def replace_metacharacters(pattern):
"""Remove unescaped metacharacters from the pattern."""
return pattern.replace('^', '').replace('$', '').replace('?', '')
return re.sub(
r'((?:^|(?<!\\))(?:\\\\)*)(\\?)([?^$])',
lambda m: m[1] + m[3] if m[2] else m[1],
pattern,
)
def replace_named_groups(pattern):

View File

@ -409,6 +409,34 @@ class AdminDocViewFunctionsTests(SimpleTestCase):
(r'a???', '/a'),
# Multiple mixed metacharacters.
(r'^a/?$', '/a/'),
# Escaped single metacharacters.
(r'\^a', r'/^a'),
(r'\\^a', r'/\\a'),
(r'\\\^a', r'/\\^a'),
(r'\\\\^a', r'/\\\\a'),
(r'\\\\\^a', r'/\\\\^a'),
(r'a\$', r'/a$'),
(r'a\\$', r'/a\\'),
(r'a\\\$', r'/a\\$'),
(r'a\\\\$', r'/a\\\\'),
(r'a\\\\\$', r'/a\\\\$'),
(r'a\?', r'/a?'),
(r'a\\?', r'/a\\'),
(r'a\\\?', r'/a\\?'),
(r'a\\\\?', r'/a\\\\'),
(r'a\\\\\?', r'/a\\\\?'),
# Escaped mixed metacharacters.
(r'^a\?$', r'/a?'),
(r'^a\\?$', r'/a\\'),
(r'^a\\\?$', r'/a\\?'),
(r'^a\\\\?$', r'/a\\\\'),
(r'^a\\\\\?$', r'/a\\\\?'),
# Adjacent escaped metacharacters.
(r'^a\?\$', r'/a?$'),
(r'^a\\?\\$', r'/a\\\\'),
(r'^a\\\?\\\$', r'/a\\?\\$'),
(r'^a\\\\?\\\\$', r'/a\\\\\\\\'),
(r'^a\\\\\?\\\\\$', r'/a\\\\?\\\\$'),
)
for pattern, output in tests:
with self.subTest(pattern=pattern):