【问题标题】:stringr - remove multiple spaces, but keep linebreaks (\n, \r)stringr - 删除多个空格,但保留换行符 (\in, \r)
【发布时间】:2020-07-01 14:03:36
【问题描述】:

我正在处理一些原始文本,并想用一个空格替换所有多个空格。通常,会使用 stringr 的 str_squish,但不幸的是它还删除了我必须保留的换行符(\n 和 \r)。

有什么想法吗?在我的尝试之下。非常感谢!

library(tidyverse)
x <- "hello     \n\r how are you \n\r    all good?"
str_squish(x)
#> [1] "hello how are you all good?"
str_replace_all(x, "[:space:]+", " ")
#> [1] "hello how are you all good?"
str_replace_all(x, "\\s+", " ")
#> [1] "hello how are you all good?"

reprex package (v0.3.0) 于 2020-07-01 创建

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    使用stringr,您可以使用\h 速记字符类来匹配任何水平空格。

    library(stringr)
    x <- "hello     \n\r how are you \n\r    all good?"
    x <- str_replace_all(x, "\\h+", " ")
    ## [1] "hello \n\r how are you \n\r all good?"
    

    在基础 R 中,您也可以将它与 PCRE 模式一起使用:

    gsub("\\h+", " ", x, perl=TRUE)
    

    请参阅online R demo

    如果您打算仍然匹配除 CR 和 LF 符号之外的任何空格(包括一些 Unicode 换行符),您可以直接使用 [^\S\r\n] 模式:

    str_replace_all(x, "[^\\S\r\n]+", " ")
    gsub("[^\\S\r\n]+", " ", x, perl=TRUE)
    

    【讨论】:

      【解决方案2】:

      您可以只在正则表达式中使用文字空间,而不是 \\s[:space:]

      str_replace_all(x, " +", " ") %>%
          cat()
      
      hello 
       how are you 
       all good?
      

      您还可以使用[ \t][:blank:]\\h 代替 来包含选项卡。在这种情况下,您可能希望使用 {2,} 选择 2 个或多个相同的选择器,这样您就不必编写两次模式(即 [:blank:][:blank:]+):

      y <- "hello     \n\r\t\thow are you \n\r    all   good?"
      
      str_replace_all(y, "[:blank:]{2,}", " ") %>%
          cat()
      
      hello 
       how are you 
       all good?
      

      【讨论】:

      • 还有[[:blank:]] 删除空格和制表符。由于 OP 只想在有两个或更多空格时替换,因此您也可以明确声明 [[:blank:]]{2,},尽管您显然会得到相同的结果。
      猜你喜欢
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多