我有一个 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)]逻辑是:如果正则表达式搜索返回任何内容,我将找到找到的组,这意味着它不是无。问题是,行为很奇怪——我可以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)]
1 回答
隔江千里
TA贡献1906条经验 获得超10个赞
删除.group() is not None. 如果没有任何匹配项,re.search()则返回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)'>]
添加回答
举报
0/150
提交
取消