我知道你可以删除尾随和前导空格
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)
这是一个选项:
gsub("^ +| +$|( ) +", "\\1", testString) # with Frank's input, and Agstudy's style
Run Code Online (Sandbox Code Playgroud)
我们使用捕获组来确保将多个内部空间替换为单个空间.\\s
如果您希望删除非空格空格,请将""更改为.
使用积极的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)
您只需添加\\s+(?=\\s)
到原始正则表达式:
gsub("^\\s+|\\s+$|\\s+(?=\\s)", "", x, perl=T)
Run Code Online (Sandbox Code Playgroud)
见DEMO
归档时间: |
|
查看次数: |
1283 次 |
最近记录: |