我知道您可以使用
删除尾随和前导空格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)
答案 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)
答案 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."