用于在列表理解中过滤正则表达式搜索的海象运算符
Walrus operator for filtering regex searches in list comprehension
我有一个 Python 字符串列表。我想对每个元素进行正则表达式搜索,只过滤那些我设法捕获正则表达式组的元素。我想我只能使用 Python 3.8 中的海象运算符进行正则表达式搜索一次。到目前为止我有:
attacks = [match
for attack in attacks
if (match := re.search(r"(\([0-9]+d[\s\S]+\))", attack).group() is not None)]
逻辑是:如果正则表达式搜索返回任何内容,我将找到找到的组,这意味着它不是 None。问题是,行为很奇怪——我可以在这个列表理解之前 print()
,程序以代码 0 结束,但是没有结果,在列表理解之后 print()
不起作用。我做错了什么?
编辑:
完整代码:
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) "
if attacks:
attacks = attacks.group().split(")")
attacks = [match
for attack in attacks
if (match := re.search(r"(\([0-9]+d[\s\S]+\))", attack).group() is not None)]
删除 .group() is not None
。如果没有任何匹配项,re.search()
returns None
并抛出异常:
import re
attacks = ['(7dW)', 'xxx']
attacks = [match
for attack in attacks
if (match := re.search(r"(\([0-9]+d[\s\S]+\))", attack))]
print(attacks)
打印:
[<re.Match object; span=(0, 5), match='(7dW)'>]
我有一个 Python 字符串列表。我想对每个元素进行正则表达式搜索,只过滤那些我设法捕获正则表达式组的元素。我想我只能使用 Python 3.8 中的海象运算符进行正则表达式搜索一次。到目前为止我有:
attacks = [match
for attack in attacks
if (match := re.search(r"(\([0-9]+d[\s\S]+\))", attack).group() is not None)]
逻辑是:如果正则表达式搜索返回任何内容,我将找到找到的组,这意味着它不是 None。问题是,行为很奇怪——我可以在这个列表理解之前 print()
,程序以代码 0 结束,但是没有结果,在列表理解之后 print()
不起作用。我做错了什么?
编辑:
完整代码:
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) "
if attacks:
attacks = attacks.group().split(")")
attacks = [match
for attack in attacks
if (match := re.search(r"(\([0-9]+d[\s\S]+\))", attack).group() is not None)]
删除 .group() is not None
。如果没有任何匹配项,re.search()
returns None
并抛出异常:
import re
attacks = ['(7dW)', 'xxx']
attacks = [match
for attack in attacks
if (match := re.search(r"(\([0-9]+d[\s\S]+\))", attack))]
print(attacks)
打印:
[<re.Match object; span=(0, 5), match='(7dW)'>]