0

我有一个 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)]
4

1 回答 1

3

删除.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)'>]
于 2020-08-14T13:08:36.453 回答