【问题标题】:how to delete a space between a number and a character using r and stringr如何使用 r 和 stringr 删除数字和字符之间的空格
【发布时间】:2017-03-15 06:53:42
【问题描述】:

我正在使用 R 和 stringr 进行一些字符串替换。我的文字就像“xxxxxx xxxx xxxxxx 1.5L xxxxx”或“xxxxxx xxxx xxxxxx 1.5 L xxxxx”。我的问题是:如何删除 1.5 和 L 之间的空格?或如何在它们之间添加空格?非常感谢。

【问题讨论】:

  • stringr::str_replace_all(c("xxxxxx xxxx xxxxxx 1.5L xxxxx", "xxxxxx xxxx xxxxxx 1.5 L xxxxx"), '(\\d) (\\w)', '\\1\\2'),或者使用环视,或者只是坚持gsub
  • 谢谢!效果很好

标签: r regex replace stringr


【解决方案1】:

我们可以使用库(stringi)

library(stringi)

text <- "1.5 L"
stri_replace_all(text,"1.5L" ,fixed = "1.5 L" )


[1] "1.5L

【讨论】:

    【解决方案2】:

    这应该可以工作

    replacer=function(x)
    {
      match_term=str_replace(str_match(x,'(?:[0-9]|\\.)+(?: +)([A-Z])')[,1],' +','')
      return(str_replace(x,'([0-9]|\\.)+( +)([A-Z])',match_term))
    }
    

    【讨论】:

      【解决方案3】:

      我们可以使用 sub 对单个捕获组执行此操作

      sub("(\\d+)\\s+", "\\1", str1)
      #[1] "xxxxxx xxxx xxxxxx 1.5L xxxxx" "xxxxxx xxxx xxxxxx 1.5L xxxxx"
      

      数据

      str1 <- c("xxxxxx xxxx xxxxxx 1.5L xxxxx" , "xxxxxx xxxx xxxxxx 1.5 L xxxxx")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 2015-03-12
        • 2020-07-29
        • 2013-01-16
        • 2013-09-23
        相关资源
        最近更新 更多