I have a Python list of strings. I want to do the regex search on each element, filtering only those elements where I managed to capture the regex group. I think I can do the regex search only once using the walrus operator from Python 3.8. So far I have:
JavaScript
x
4
1
attacks = [match
2
for attack in attacks
3
if (match := re.search(r"(([0-9]+d[sS]+))", attack).group() is not None)]
4
The logic is: I take the found group if the regex search returned anything, which means it is not None. The problem is, the bevahiour is weird – I can print()
before this list comprehension, the program finishes with code 0, but there is no result and print()
after the list comprehension does not work. What am I doing wrong?
EDIT:
Full code:
JavaScript
1
7
1
text = "Speed 30 ft. Melee short sword +3 (1d6+1/19-20) Ranged light crossbow +3 (1d8/19-20) Special Attacks sneak attack +1d6 Spell-Like Abilities (CL 1st) "
2
if attacks:
3
attacks = attacks.group().split(")")
4
attacks = [match
5
for attack in attacks
6
if (match := re.search(r"(([0-9]+d[sS]+))", attack).group() is not None)]
7
Advertisement
Answer
Remove the .group() is not None
. If there isn’t any match, re.search()
returns None
and exception is thrown:
JavaScript
1
10
10
1
import re
2
3
4
attacks = ['(7dW)', 'xxx']
5
attacks = [match
6
for attack in attacks
7
if (match := re.search(r"(([0-9]+d[sS]+))", attack))]
8
9
print(attacks)
10
Prints:
JavaScript
1
2
1
[<re.Match object; span=(0, 5), match='(7dW)'>]
2