are*_*ddy 2 regex string replace r gsub
我有以下字符串:
str<-c("hello(world(howr u doin")
Run Code Online (Sandbox Code Playgroud)
我想删除单词"hello(来自字符串的世界(howr).我想要我的输出
str2<-c("u doin")
Run Code Online (Sandbox Code Playgroud)
我通过使用获得的错误
gsub("hello(world(howr","", str)
Run Code Online (Sandbox Code Playgroud)
是:表达无效,原因'缺失')''
请注意,我不会在字符串的迭代中使用此函数,我们无法说出字符串中的"(")位置.因此,我会请求您提供全局解决方案.谢谢.另外,我会请求您要注意的是,字符串中要删除的单词在不同的时间可能会有所不同.所以我想要一个正则表达式,它告诉忽略要删除的单词中特殊字符的含义.
这是一个现实世界的情况
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)
}
Run Code Online (Sandbox Code Playgroud)
我的预期产量是
text_sa<-as.String("`$%`$> http://t.co/W9wDz8yhZE @villan_TKRrength!")
Run Code Online (Sandbox Code Playgroud)
你需要转义括号,因为括号是正则表达式中的特殊字符.由于更换只会发生一次,您不需要去gsub
.sub
单独就足够了.
sub("hello\\(world\\(howr\\s*","", str)
Run Code Online (Sandbox Code Playgroud)
要么
sub("^\\S+\\s*", "", str)
Run Code Online (Sandbox Code Playgroud)
编辑:
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! "
Run Code Online (Sandbox Code Playgroud)