【问题标题】:Replacing string variable with punctuation in R without removing other string在R中用标点符号替换字符串变量而不删除其他字符串
【发布时间】:2020-02-08 12:12:22
【问题描述】:

在 R 中,我无法替换带有标点符号的子字符串。即在字符串“r.Export”中,我试图替换“r”。用“报告”。我用过 gsub,下面是我的代码:

string <- "r.Export"
short <- "r."
replacement <- "Report."

gsub(short,replacement,string)

所需的输出是:“Report.Export”,但是 gsub 似乎替换了第二个 r,因此输出是:

Report.ExpoReport.

使用 sub() 也不是解决方案,因为我正在执行多个 gsub,有时要替换的字符串是:

short <- "o."

所以,无论如何,r.Export 中的 o 都被替换了,变得一团糟。

【问题讨论】:

    标签: r string replace


    【解决方案1】:
    string <- "r.Export"
    short <- "r\\."
    replacement <- "Report."
    
    gsub(short,replacement,string)
    

    返回:

    [1] "Report.Export"
    

    或者,使用fixed=TRUE

    string <- "r.Export"
    short <- "r."
    replacement <- "Report."
    
    gsub(short,replacement,string, fixed=TRUE)
    

    返回:

    [1] "Report.Export"
    

    解释:没有fixed=TRUE 参数,gsub 需要一个正则表达式作为第一个参数。使用正则表达式. 是“任何字符”的占位符。如果您想要文字 .(句点),则必须使用 \\.(即转义句点)或上述参数 fixed=TRUE

    【讨论】:

    • 完美fixed=TRUE 是我一直在寻找的,谢谢。我可能应该更清楚地阅读文档。
    【解决方案2】:

    由于您的模式 (.) 中有字符在正则表达式中具有特殊含义,因此请使用与字符串原样匹配的 fixed = TRUE

    gsub(short,replacement,string, fixed = TRUE)
    #[1] "Report.Export"
    

    【讨论】:

      【解决方案3】:

      我实际上可能会在此处添加单词边界和前瞻,以确保尽可能有针对性地匹配:

      string <- "r.Export"
      replacement <- "Report."
      output <- gsub("\\br\\.(?=\\w)", replacement, string, perl=TRUE)
      output
      
      [1] "Report.Export"
      

      这种方法确保我们只匹配r.,当r 前面有空格或者是字符串的开头,并且当点后面是另一个单词时。考虑句子 The project r.Export needed a programmer. 在这种情况下,我们不想替换最后的 r.

      【讨论】:

        【解决方案4】:

        我们可以使用sub

        sub(short,replacement,string, fixed = TRUE)
        #[1] "Report.Export"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-30
          • 1970-01-01
          • 1970-01-01
          • 2017-07-26
          相关资源
          最近更新 更多