现在我真的找不到标题的方法,但我可以用代码解释我要做什么。
所以我可以接受用户评论并检查它是否具有这些“[[Keyword]]”修饰符。现在我想进一步扩展它以允许多个。
如果用户在当前代码行中输入多个修饰符,就会发生这种情况。
#comment in this case is "I want to [[find]] [[this]] [[Special]] word."
# c is the comment.
body = c.body
# Finds the hot word
result = re.search("\[\[(.*)\]\]", body, re.IGNORECASE)
print(result)
预期结果:
>>>find this Special
返回结果:
>>>find]] [[this]] [[Special
有什么办法可以把每个结果都放入某种数组中,这样我就可以测量数组的长度,每个结果都对应一个数字
我希望它如何工作。
print(result[0] +'\n')
print(result[1] +'\n')
print(result[2] +'\n')
>>>find
>>>this
>>>Special
最佳答案
.*
默认是greedy。您希望它以非贪婪 模式匹配,以便尽可能少地匹配。您可以使用 .*?
而不是 .*
来做到这一点。您还应该使用 re.findall
来获取所有匹配项,而不是 re.search
,后者只会返回第一个匹配项。
>>> re.findall(r"\[\[(.*?)\]\]", body, re.IGNORECASE)
['find', 'this', 'special']
关于python - 从段落中提取热字符之间的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37847967/