str_replace(package stringr)无法替换r中的括号?
题
我有一个字符串,说
fruit <- "()goodapple"
.
我想删除字符串中的括号。我决定使用Stringr包,因为它通常可以处理这种问题。我使用:
str_replace(fruit,"()","")
.
但没有更换任何内容,替换以下内容:
[1] "()good"
.
如果我只想更换右半括号,它可以工作:
str_replace(fruit,")","")
[1] "(good"
.
但是,左半括号不起作用:
str_replace(fruit,"(","")
.
和以下错误显示:
Error in sub("(", "", "()good", fixed = FALSE, ignore.case = FALSE, perl = FALSE) :
invalid regular expression '(', reason 'Missing ')''
.
任何人都有想法,为什么会发生这种情况?如何删除字符串中的“()”,然后删除?
解决方案
逃避括号...
str_replace(fruit,"\\(\\)","")
# [1] "goodapple"
.
您可能还想考虑探索 “stringi”包 ,它具有类似的方法“stringr”,但具有更灵活的功能。例如,有生成的icetagcode,它在这里很有用,因为您的搜索字符串是固定模式,而不是正则表达式模式:
library(stringi)
stri_replace_all_fixed(fruit, "()", "")
# [1] "goodapple"
.
当然,基本的
stri_replace_all_fixed
也很好地处理:
gsub("()", "", fruit, fixed=TRUE)
# [1] "goodapple"
. 其他提示
接受的答案适用于您的确切问题,但不是更一般的问题:
my_fruits <- c("()goodapple", "(bad)apple", "(funnyapple")
str_replace(my_fruits,"\\(\\)","")
## "goodapple" "(bad)apple", "(funnyapple"
.
这是因为正则匹配的正则匹配“(”后跟一个“)”。
假设您只关心括号对,这是一个更强大的解决方案:
str_replace(my_fruits, "\\([^()]{0,}\\)", "")
## "goodapple" "apple" "(funnyapple"
. 关闭MJH的答案,这会删除所有(或):
my_fruits <- c("()goodapple", "(bad)apple", "(funnyapple")
str_replace_all(my_fruits, "[//(//)]", "")
[1] "goodapple" "badapple" "funnyapple"
. 不隶属于 StackOverflow