I want to re.search
within an if statement but regardless of identation, get syntax error. Is it because elif:
has no condition?
fr = re.compile(r'(long_regex)', flags = re.DOTALL | re.MULTILINE) fra = fr.search(text) if fra: result = fra.group(5) elif: f3 = re.compile(r'(some_regex_1)', flags = re.DOTALL | re.MULTILINE) fr3 = f3.search(text) result = fr3.group(5) elif: f4 = re.compile(r'(some_regex)', flags = re.DOTALL | re.MULTILINE) fr4 = f4.search(text) result = fr4.group(4) else: result = None
error message
Input In [102] elif: ^ SyntaxError: invalid syntax
Advertisement
Answer
In elif
you have if
, it requires a condition and you provide none, it should be
if condition1: pass elif condition2: pass
Using walrus operator (since py3.8) you can improve your code to look like
if fra := re.search(r'(long_regex)', text, flags=re.DOTALL | re.MULTILINE): result = fra.group(5) elif fr3 := re.search(r'(some_regex_1)', text, flags=re.DOTALL | re.MULTILINE): result = fr3.group(5) elif fr4 := re.search(r'(some_regex)', text, flags=re.DOTALL | re.MULTILINE): result = fr4.group(4) else: result = None
If the code is executed multiple times, it should be better to compile the regex onces
Define the compiled regex globally in the file
F2 = re.compile(r'(long_regex)', flags=re.DOTALL | re.MULTILINE) F3 = re.compile(r'(some_regex_1)', flags=re.DOTALL | re.MULTILINE) F4 = re.compile(r'(some_regex)', flags=re.DOTALL | re.MULTILINE)
Then use it in your methods
if fra := F2.search(text): result = fra.group(5) elif fr3 := F3.search(text): result = fr3.group(5) elif fr4 := F4.search(text): result = fr4.group(4) else: result = None