亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當第一個單詞完全匹配時返回完整的句子

當第一個單詞完全匹配時返回完整的句子

翻過高山走不出你 2022-11-18 16:48:32
我試圖僅在第一個單詞與我所需的單詞匹配時才返回全文。在這個例子中,我的詞是“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)這在找到句子時效果很好。它將結果作為帶有文本的列表返回。我的問題是當沒有匹配項時,結果返回一個空列表。有沒有一種方法,當沒有匹配項時,我什么也得不到。我不需要空字符串。我可以用其他東西代替 findall 嗎?
查看完整描述

1 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

我認為您正在尋找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


查看完整回答
反對 回復 2022-11-18
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號