我試圖僅在第一個單詞與我所需的單詞匹配時才返回全文。在這個例子中,我的詞是“sparta”"sparta where is fire" -> this should return me the whole sentence "Hey sparta where is fire" -> this should not return me anything as the sentence did not started with the Sparta我正在用 python 編寫,直到這一點:text = "sparta where is fire"my_regex = "^[sparta\s]+ [\w\s]+"result = re.findall(my_regex, text)這在找到句子時效果很好。它將結(jié)果作為帶有文本的列表返回。我的問題是當(dāng)沒有匹配項時,結(jié)果返回一個空列表。有沒有一種方法,當(dāng)沒有匹配項時,我什么也得不到。我不需要空字符串。我可以用其他東西代替 findall 嗎?
1 回答

千萬里不及你
TA貢獻(xiàn)1784條經(jīng)驗 獲得超9個贊
我認(rèn)為您正在尋找match功能。
text = "sparta where is fire"
my_regex = "^[sparta\s]+ [\w\s]+"
match = re.match(my_regex, text)
match.group() # returns "sparta where is fire"
match2 = re.match(my_regex, "Hello")
match2 # None
添加回答
舉報
0/150
提交
取消