【问题标题】:str_replace (package stringr) cannot replace brackets in r?str_replace (package stringr) 不能替换 r 中的括号?
【发布时间】:2014-04-14 16:32:19
【问题描述】:

我有一个字符串,比如说

 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 ')''

有人知道为什么会这样吗?那么如何删除字符串中的“()”呢?

【问题讨论】:

    标签: r stringr


    【解决方案1】:

    转义括号就可以了...

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

    您可能还想考虑探索"stringi" package,它具有与“stringr”类似的方法,但具有更灵活的功能。例如,stri_replace_all_fixed 在这里很有用,因为您的搜索字符串是固定模式,而不是正则表达式模式:

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

    当然,基本的gsub 也可以很好地处理这个问题:

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

    【讨论】:

      【解决方案2】:

      接受的答案适用于您的确切问题,但不适用于更普遍的问题:

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

      这是因为正则表达式完全匹配“(”后跟“)”。

      假设您只关心括号对,这是一个更强大的解决方案:

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

      【讨论】:

        【解决方案3】:

        根据 MJH 的回答,这将删除所有(或):

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-07-22
          • 1970-01-01
          • 1970-01-01
          • 2023-02-23
          • 2016-09-27
          • 2017-11-17
          • 1970-01-01
          相关资源
          最近更新 更多