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

C_Z*_*_Z_ 11 regex r

我知道你可以删除尾随和前导空格

gsub("^\\s+|\\s+$", "", x)
Run Code Online (Sandbox Code Playgroud)

你可以删除内部空间

gsub("\\s+"," ",x)
Run Code Online (Sandbox Code Playgroud)

我可以将它们组合成一个函数,但我想知道是否有办法只使用一个gsub函数

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

testString<- "  This is a      test. "

trim(testString)
Run Code Online (Sandbox Code Playgroud)

Bro*_*ieG 9

这是一个选项:

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

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


ags*_*udy 8

使用积极的lookbehind:

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

说明:

## "^ *"     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 
Run Code Online (Sandbox Code Playgroud)


kar*_*ala 6

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

gsub("^\\s+|\\s+$|\\s+(?=\\s)", "", x, perl=T)
Run Code Online (Sandbox Code Playgroud)

DEMO