From c834c356f72d07e03ad8ece49f72ebb4ee8759b4 Mon Sep 17 00:00:00 2001 From: "Jason R. Coombs" Date: Fri, 29 Mar 2024 14:49:49 -0400 Subject: [PATCH] Use a regular expression to search for the first match. Avoids mutating variables and tricky logic and over-computing all of the starts when only the first is relevant. --- Lib/configparser.py | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/Lib/configparser.py b/Lib/configparser.py index 591896d20cff36..d0326c60e9b907 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -572,19 +572,16 @@ def has_comments(self): return self.strip() != self.clean def _strip_inline(self): - starts = [] - prefixes = {p: -1 for p in self.prefixes.inline} - while not starts and prefixes: - next_prefixes = {} - for prefix, index in prefixes.items(): - index = self.find(prefix, index+1) - if index == -1: - continue - next_prefixes[prefix] = index - if index == 0 or (index > 0 and self[index-1].isspace()): - starts.append(index) - prefixes = next_prefixes - return self[:min(starts, default=None)].strip() + """ + Search for the earliest prefix at the beginning of the line or following a space. + """ + matcher = re.compile( + '|'.join(fr'(^|\s)({re.escape(prefix)})' for prefix in self.prefixes.inline) + # match nothing if no prefixes + or '(?!)' + ) + match = matcher.search(self) + return self[:match.start() if match else None].strip() def _strip_full(self): return '' if any(map(self.strip().startswith, self.prefixes.full)) else True