识别关键字后删除后续单词

时间:2018-12-30 22:41:36

标签: python regex python-3.x string

我正在尝试使用正则表达式,并想知道是否有任何方法可以删除我识别出的单词之后的紧接着的单词。

例如,

text = "This is the full sentence that I wish to apply regex on."

如果我想删除“ full”一词,我了解我可以执行以下操作:

result = re.sub(r"full", "", text)  

那会给我

This is the sentence that I wish to apply regex on.

有什么办法可以从我上面的文字中获得以下声明? (例如,保留单词“ full”之后的第5个单词,或删除“ full”后的前5个单词)

apply regex on.

1 个答案:

答案 0 :(得分:0)

匹配从开头到字符串再到full的所有内容,然后重复一组\s\S+ 5次以匹配5个单词,并将整个匹配项替换为空字符串:

^.*?full(?:\s\S+){5}\s

https://regex101.com/r/H6tdCH/1

相关问题