如何删除r中字符串中带有“(”的单词?

how to remove words with "(" in a string in r?

我有以下字符串:

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

我想从字符串中删除单词 "hello(world(howr"。我希望我的输出是

str2<-c("u doin")

我使用

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

是:无效表达式,原因'Missing ')''

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

这是真实世界的情况

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

我的预期输出是

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

您需要转义方括号,因为方括号是正则表达式中的特殊字符。由于替换只会发生一次,因此您无需执行 gsubsub一个就够了。

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

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

编辑:

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