首页 > 解决方案 > 使用正则表达式来阻止单词

问题描述

我正在尝试使用正则表达式来阻止文本中的单词。

c <- "Foo is down. No one wants Foos after this. Before, people liked Fooy a lot."

期望的输出:

"Foo is down. No one wants Foo after this. Before, people liked Foo a lot."

我需要保留单词Foo,但删除该单词后面的所有字符,保留字符串的其余部分。

我设法将后缀从单词的基础中分离出来,我可以在单词“Foo”的变体之后删除所有内容,并且我尝试了单词边界,但无法弄清楚如何获得所需的输出。

标签: rregexgsub

解决方案


我们可以尝试使用空字符串gsub替换模式:(?<=Foo)\S+

x <- "Foo is down. No one wants Foos after this. Before, people liked Fooy a lot."
output <- gsub("(?<=Foo)\\S+", "", x, perl=TRUE)
output

[1] "Foo is down. No one wants Foo after this. Before, people liked Foo a lot."

演示


推荐阅读