使用一个gsub调用去除尾部和首部空格以及额外的内部空格。

11

我知道您可以使用

trim()

函数来删除字符串中的尾随和前导空格。

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个回答

9
这里有一个选项:
gsub("^ +| +$|( ) +", "\\1", testString)  # with Frank's input, and Agstudy's style

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

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 

6
您只需在原始正则表达式中添加\\s+(?=\\s)即可:
gsub("^\\s+|\\s+$|\\s+(?=\\s)", "", x, perl=T)

查看 演示


4

您要求使用gsub选项并获得了很好的选项。还有来自“qdapRegex”的rm_white_multiple

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

1
如果不使用gsub也可以接受答案,那么下面的方法可以实现。它不使用任何正则表达式:
paste(scan(textConnection(testString), what = "", quiet = TRUE), collapse = " ")

提供:

[1] "This is a test."

0

你也可以使用嵌套的gsub。虽然不如之前的答案优雅。

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

1
这不是和OP的函数类似吗? - akrun
这只是一行代码 :) - Alexey Ferapontov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接