为了账号安全,请及时绑定邮箱和手机立即绑定

当第一个单词完全匹配时返回完整的句子

当第一个单词完全匹配时返回完整的句子

翻过高山走不出你 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 关注
  • 115 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号