1
You're calling re.search()
twice, once to check if there's a match, and again to get .group(1)
. Instead, store the match in a variable:
match = re.search(r'data check\s*:\s*false\((\d+)\)', content)
result = match.group(1) if match else "NA"
If you're running the same regex many times (in a loop or on multiple lines), compile it once:
pattern = re.compile(r'data check\s*:\s*false\((\d+)\)')
match = pattern.search(content)
result = match.group(1) if match else "NA"
If you're matching multiple regexes on the same input and each has a similar pattern :
patterns = {
"data_check_false": re.compile(r'data check\s*:\s*false\((\d+)\)'),
"another_check": re.compile(r'another pattern\s*:\s*(\d+)'),
}
results = {}
for name, pattern in patterns.items():
match = pattern.search(content)
results[name] = match.group(1) if match else "NA"
0
match = re.search(r'data check\s*:\s*false\((\d+)\)', content)
result = match.group(1) if match else "NA"
re.search(...)
looks for the pattern data check : false(<number>)
in the content
string.
- If a match is found,
group(1)
extracts the number inside the parentheses.
- If no match is found, it returns
"NA"
.