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

2024-03-29 05:50:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图仅在第一个单词与所需单词匹配时返回全文。 在这个例子中,我的词是“斯巴达”

"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)

当它找到这个句子时,效果非常好。它以列表的形式返回结果和文本。我的问题是当没有匹配项时,结果返回一个空列表。有没有一种方法,当没有比赛时,我什么也得不到。我不需要空字符串。还有什么可以代替芬德尔的吗


Tags: thetextreturnismynotthiswhere
1条回答
网友
1楼 · 发布于 2024-03-29 05:50:18

我认为您正在寻找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

相关问题 更多 >