我有一個 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
提交
取消