使用一个gsub调用删除尾随和前导空格以及额外的内部空格

时间:2015-06-10 17:25:16

标签: regex r

我知道您可以使用

删除尾随和前导空格
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)

6 个答案:

答案 0 :(得分:9)

这是一个选项:

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

我们使用捕获组来确保多个内部空间被单个空格替换。改变&#34; &#34;如果您希望删除非空格空格,请\\s

答案 1 :(得分:8)

使用积极的外观:

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 

答案 2 :(得分:6)

您只需将\\s+(?=\\s)添加到原始正则表达式:

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

请参阅DEMO

答案 3 :(得分:4)

您已经要求gsub选项并获得了不错的选择。 “qdapRegex”中还有rm_white_multiple

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

答案 4 :(得分:1)

如果未使用gsub的答案可以接受,则以下操作。它不使用任何正则表达式:

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

,并提供:

[1] "This is a test."

答案 5 :(得分:0)

您还可以使用嵌套的gsub。比之前的答案更不优雅

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