str_replace (package stringr) cannot replace brackets in r?

孤者浪人 提交于 2019-12-01 04:36:47

Escaping the parentheses does it...

str_replace(fruit,"\\(\\)","")
# [1] "goodapple"

You may also want to consider exploring the "stringi" package, which has a similar approach to "stringr" but has more flexible functions. For instance, there is stri_replace_all_fixed, which would be useful here since your search string is a fixed pattern, not a regex pattern:

library(stringi)
stri_replace_all_fixed(fruit, "()", "")
# [1] "goodapple"

Of course, basic gsub handles this just fine too:

gsub("()", "", fruit, fixed=TRUE)
# [1] "goodapple"

The accepted answer works for your exact problem, but not for the more general problem:

my_fruits <- c("()goodapple", "(bad)apple", "(funnyapple")
str_replace(my_fruits,"\\(\\)","")
## "goodapple"  "(bad)apple", "(funnyapple"

This is because the regex exactly matches a "(" followed by a ")".

Assuming you care only about bracket pairs, this is a stronger solution:

str_replace(my_fruits, "\\([^()]{0,}\\)", "")
## "goodapple"   "apple"       "(funnyapple"

Building off of MJH's answer, this removes all ( or ):

my_fruits <- c("()goodapple", "(bad)apple", "(funnyapple")
str_replace_all(my_fruits, "[//(//)]", "")

[1] "goodapple"  "badapple"   "funnyapple"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!