【问题标题】:Remove trailing and leading spaces and extra internal whitespace with one gsub call使用一次 gsub 调用删除尾随和前导空格以及额外的内部空格
【发布时间】:2015-06-10 17:25:15
【问题描述】:

我知道您可以使用

删除尾随和前导空格
gsub("^\\s+|\\s+$", "", x)

你可以删除内部空格

gsub("\\s+"," ",x)

我可以将这些组合成一个函数,但我想知道是否有一种方法可以只使用一次 gsub 函数

trim <- function (x) {
  x <- gsub("^\\s+|\\s+$|", "", x)
  gsub("\\s+", " ", x)
}

testString<- "  This is a      test. "

trim(testString)

【问题讨论】:

    标签: regex r


    【解决方案1】:

    这是一个选项:

    gsub("^ +| +$|( ) +", "\\1", testString)  # with Frank's input, and Agstudy's style
    

    我们使用捕获组来确保多个内部空格被单个空格替换。如果您希望删除非空格空格,请将“”更改为 \\s

    【讨论】:

      【解决方案2】:

      使用积极的向后看:

      gsub("^ *|(?<= ) | *$",'',testString,perl=TRUE)
      # "This is a test."
      

      解释:

      ## "^ *"     matches any leading space 
      ## "(?<= ) "    The general form is (?<=a)b : 
                   ## matches a "b"( a space here)
                   ## that is preceded by "a" (another space here)
      ## " *$"     matches trailing spaces 
      

      【讨论】:

        【解决方案3】:

        您可以将\\s+(?=\\s) 添加到您原来的正则表达式中:

        gsub("^\\s+|\\s+$|\\s+(?=\\s)", "", x, perl=T)
        

        DEMO

        【讨论】:

          【解决方案4】:

          您已请求gsub 选项并获得了不错的选项。还有来自“qdapRegex”的rm_white_multiple

          > testString<- "  This is a      test. "
          > library(qdapRegex)
          > rm_white_multiple(testString)
          [1] "This is a test."
          

          【讨论】:

            【解决方案5】:

            如果不使用gsub 的答案是可以接受的,那么下面会这样做。它不使用任何正则表达式:

            paste(scan(textConnection(testString), what = "", quiet = TRUE), collapse = " ")
            

            给予:

            [1] "This is a test."
            

            【讨论】:

              【解决方案6】:

              您也可以使用嵌套的gsub。没有以前的答案那么优雅

              > gsub("\\s+"," ",gsub("^\\s+|\\s$","",testString))
              [1] "This is a test."
              

              【讨论】:

              • 这不是和OP的功能类似
              • 它是,但在一行:)
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-02-28
              • 1970-01-01
              • 2018-10-04
              • 2012-05-17
              • 1970-01-01
              • 2020-08-20
              • 2013-07-20
              相关资源
              最近更新 更多