使用正则表达式阻止单词

时间:2018-10-09 23:15:12

标签: r regex gsub

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

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”变体后的所有内容,并尝试了单词边界,但无法弄清楚如何获得所需的输出。

2 个答案:

答案 0 :(得分:1)

我们可以尝试使用public enum name { James(1,2,3) Taylor(2,3,4) Mary(5,6,7); } 并将模式gsub替换为空字符串:

(?<=Foo)\S+

Demo

答案 1 :(得分:0)

一个可能解决此问题的正则表达式用“ Foo”代替“ Foo后有一个或多个字母”:

> x = "Foo is down. No one wants Foos after this. Before, people liked Fooy a lot."
> stringr::str_replace_all(x, "Foo[a-z]+", "Foo")
[1] "Foo is down. No one wants Foo after this. Before, people liked Foo a lot."