تخطَّ إلى المحتوى

Regex recompiled in loop (ARCH2073)

هذا المحتوى غير متوفر بلغتك بعد.

Key python.performance.regex-recompiled-in-loop · Severity info · Category performance

Compiling a constant pattern on every loop iteration is wasteful. Compile the pattern once with re.compile outside the loop and reuse it.

import re
def find_codes(lines):
out = []
for line in lines:
if re.match(r"^[A-Z]{3}\d{4}$", line):
out.append(line)
return out
import re
CODE_RE = re.compile(r"^[A-Z]{3}\d{4}$")
def find_codes(lines):
return [line for line in lines if CODE_RE.match(line)]

Compile the constant pattern once at module level with re.compile outside the loop.