Python Re模块:在特定词后查找词

Python Re module: find words after specific word

我想用 re 模块搜索特定单词后的单词。 (不使用列表理解)

sentence = "I like you, I like your smile, I like stack o v e r flow"

# expected outcome
['you', 'your smile', 'stack o v e r flow']

我设法在 'I like' 之后得到一个单词,但是当有不同数量的单词时,我无法弄清楚如何得到整个句子。

# my code
re.compile(r'I like (\w+)').findall(sentence)

# my output
['you', 'your', 'stack']

您需要使用 [\w ]+ 而不是 \w+ 来计算空格。您也可以使用逗号分隔要分析的句子块:

>>> re.findall("I like ([\w ]+),*", sentence)

['you', 'your smile', 'stack o v e r flow']

使用这个正则表达式我得到了正确的输出:

sentence = "I like you, I like your smile, I like stack o v e r flow"
re.compile(r'I like ([\w\s]+)').findall(sentence)

您需要考虑可选的 space (\s) 以及单词字符 (\w)。此模式至少出现一次 ([\w\s]+)。