diff --git a/Lib/fnmatch.py b/Lib/fnmatch.py index 41558523a08eb8..4c31683d1f8724 100644 --- a/Lib/fnmatch.py +++ b/Lib/fnmatch.py @@ -98,6 +98,7 @@ def _translate(pat, star, question_mark): star_indices = [] i, n = 0, len(pat) + last_close = pat.rfind(']') while i < n: c = pat[i] i = i+1 @@ -111,6 +112,10 @@ def _translate(pat, star, question_mark): elif c == '?': add(question_mark) elif c == '[': + if i > last_close: + # No ']' after this point: every later '[' is a literal too. + add('\\[') + continue j = i if j < n and pat[j] == '!': j = j+1 diff --git a/Lib/test/test_fnmatch.py b/Lib/test/test_fnmatch.py index ab3561f84d568d..254ca796ea7c78 100644 --- a/Lib/test/test_fnmatch.py +++ b/Lib/test/test_fnmatch.py @@ -248,6 +248,18 @@ def test_translate(self): self.assertTrue(re.match(fatre, 'cbabcaxc')) self.assertFalse(re.match(fatre, 'dabccbad')) + def test_translate_unclosed_brackets(self): + # An unclosed '[' is a literal. Many of them used to take quadratic + # time, because each one scanned to the end of the pattern (gh-163137). + self.assertEqual(translate('[!a[b'), r'(?s:\[!a\[b)\z') + self.assertEqual(translate('[a]b[c'), r'(?s:[a]b\[c)\z') + self.assertEqual(translate(']['), r'(?s:\]\[)\z') + self.assertEqual(translate('[!]'), r'(?s:\[!\])\z') + self.assertEqual(translate('a[]b['), r'(?s:a\[\]b\[)\z') + n = 30_000 + self.assertEqual(translate('[!' * n), '(?s:' + r'\[!' * n + r')\z') + self.assertTrue(fnmatch('[!' * n, '[!' * n)) + def test_translate_wildcards(self): for pattern, expect in [ ('ab*', r'(?s:ab.*)\z'), diff --git a/Misc/NEWS.d/next/Library/2026-12-04-11-30-00.gh-issue-163137.Qf7nTz.rst b/Misc/NEWS.d/next/Library/2026-12-04-11-30-00.gh-issue-163137.Qf7nTz.rst new file mode 100644 index 00000000000000..f0a0315bfeb155 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-04-11-30-00.gh-issue-163137.Qf7nTz.rst @@ -0,0 +1,4 @@ +Fix quadratic time in :func:`fnmatch.translate` and the functions that use +it, such as :func:`fnmatch.fnmatch`, :func:`glob.translate` and +:meth:`pathlib.PurePath.full_match`, for patterns with many unclosed ``[``. +Patch by Kamal Kumar Modi.