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

问题描述 投票:0回答:1

我仅在第一个单词与所需单词匹配时才尝试返回全文。在此示例中,我的单词是“ 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使用的东西吗?

python regex
1个回答
0
投票

我认为您正在寻找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
© www.soinside.com 2019 - 2024. All rights reserved.