如何用"("在r中的字符串中删除单词?

时间:2015-10-09 08:09:57

标签: regex r string replace gsub

我有以下字符串:

str<-c("hello(world(howr u doin")

我想删除单词&#34; hello(world(howr&#34;来自字符串。我希望我的输出是

str2<-c("u doin")

使用

获得的错误
gsub("hello(world(howr","", str) 

是:表达无效,原因&#39;缺少&#39;)&#39;&#39;

请注意,我不会在字符串的迭代中使用此函数,我们不能说在哪个位置&#34;(&#34;会出现在字符串中。所以,我会要求您提供全局解决方案。谢谢。 另外,我要求您注意,字符串中要删除的单词在不同时间可能会有所不同。所以我想要一个正则表达式,它告诉我们忽略要删除的单词中特殊字符的含义。

这是一个现实世界的情况

library(stringr)
library(NLP)
library(openNLP)
text_sa<-as.String("`$%`$> http://t.co/W9wDz8yhZE @AshramOrg @villan_TKRrength! #WeSupport_`$8`$(`$>`$$`$(_`$8`$`$8`% ")
removalwords<-c("#WeSupport_`$8`$(`$>`$$`$(_`$8`$\002`$8`%", "@AshramOrg")
for(k in 1:length(removalwords)){
text_sa <- gsub(removalwords[k], "", text_sa)
}

我的预期输出是

text_sa<-as.String("`$%`$> http://t.co/W9wDz8yhZE @villan_TKRrength!")

1 个答案:

答案 0 :(得分:5)

你需要转义括号,因为括号是正则表达式中的特殊字符。由于替换只会发生一次,因此您不需要去gsub。仅sub就足够了。

sub("hello\\(world\\(howr\\s*","", str) 

sub("^\\S+\\s*", "", str)

修改

x <- "`$%`$> http://t.co/W9wDz8yhZE @AshramOrg @villan_TKRrength! #WeSupport_`$8`$(`$>`$$`$(_`$8`$`$8`% "
remove <- c("#WeSupport_`$8`$(`$>`$$`$(_`$8`$`$8`%", "@AshramOrg")
gsub(paste(gsub("([^\\w\\s])", "\\\\\\1", remove, perl=T),collapse="|"), "", x, perl=T)
[1] "`$%`$> http://t.co/W9wDz8yhZE  @villan_TKRrength!  "