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