【问题标题】:Remove all characters between two other characters (keeping the other characters)删除其他两个字符之间的所有字符(保留其他字符)
【发布时间】:2022-11-22 23:35:36
【问题描述】:

我知道这个问题已经以不同的方式多次被问到,但我找不到一个解决方案,我可以在保留边界的同时替换一些“边界”之间的文本。

input <- "this is my 'example'"
change <- "test"

现在我想用change 中的值替换单引号之间的所有内容。

预期输出为"this is my 'test'

我尝试了不同的变体:

stringr::str_replace(input, "['].*", change)

但它不起作用。例如。上面的给出了"this is my test",所以它不再有单引号了。

有任何想法吗?

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    使用sub()我们可以尝试:

    input <- "this is my 'example'"
    change <- "test"
    output <- sub("'.*?'", paste0("'", change, "'"), input)
    output
    
    [1] "this is my 'test'"
    

    【讨论】:

      【解决方案2】:

      您可以使用

      stringr::str_replace(input, "'[^']*'", paste0("'", change, "'"))
      gsub("'[^']*'", paste0("'", change, "'"), input)
      

      或者,您也可以捕获撇号然后使用反向引用,但这看起来更丑陋(参见gsub("(')[^']*(')", paste0("\1",change,"\2"), input))。

      R demo online:

      input <- "this is my 'example'"
      change <- "test"
      stringr::str_replace(input, "'[^']*'", paste0("'", change, "'"))
      gsub("'[^']*'", paste0("'", change, "'"), input)
      

      输出:

      [1] "this is my 'test'"
      [1] "this is my 'test'"
      

      笔记:如果您的 change 变量包含反斜杠,则必须将其加倍以避免出现问题:

      stringr::str_replace(input, "'[^']*'", paste0("'", gsub("\", "\\", change, fixed=TRUE), "'"))
      gsub("'[^']*'", paste0("'", gsub("\", "\\", change, fixed=TRUE), "'"), input)
      

      【讨论】:

      • 谢谢,但这给出了一个错误:Error in "'" + change : non-numeric argument to binary operator,我猜这是因为 + 号。
      • @deschen 刚刚解决了这个问题。正在玩另一种语言。
      • @deschen 我希望change 不包含像 这样需要逐字处理的子字符串。如果他们这样做,请参阅我在底部添加的注释。请参阅this demo 以更好地理解我的意思。
      猜你喜欢
      • 2019-10-27
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      相关资源
      最近更新 更多