我说有一根绳子
fruit <- "()goodapple"
Run Code Online (Sandbox Code Playgroud)
我想删除字符串中的括号.我决定使用stringr包,因为它通常可以处理这类问题.我用 :
str_replace(fruit,"()","")
Run Code Online (Sandbox Code Playgroud)
但没有任何东西被替换,以下内容被替换:
[1] "()good"
Run Code Online (Sandbox Code Playgroud)
如果我只想更换右半支架,它可以工作:
str_replace(fruit,")","")
[1] "(good"
Run Code Online (Sandbox Code Playgroud)
但是,左半支架不起作用:
str_replace(fruit,"(","")
Run Code Online (Sandbox Code Playgroud)
并显示以下错误:
Error in sub("(", "", "()good", fixed = FALSE, ignore.case = FALSE, perl = FALSE) :
invalid regular expression '(', reason 'Missing ')''
Run Code Online (Sandbox Code Playgroud)
任何人都有想法为什么会这样?如何删除字符串中的"()"呢?
A5C*_*2T1 14
逃避括号是否......
str_replace(fruit,"\\(\\)","")
# [1] "goodapple"
Run Code Online (Sandbox Code Playgroud)
您可能还想考虑探索"stringi"包,它具有与"stringr"类似的方法,但具有更灵活的功能.例如,这里stri_replace_all_fixed有用,因为您的搜索字符串是固定模式,而不是正则表达式模式:
library(stringi)
stri_replace_all_fixed(fruit, "()", "")
# [1] "goodapple"
Run Code Online (Sandbox Code Playgroud)
当然,基本gsub处理这个也很好:
gsub("()", "", fruit, fixed=TRUE)
# [1] "goodapple"
Run Code Online (Sandbox Code Playgroud)