如何使用?删除字符向量内的单词之间的额外空格?

Smi*_*ack 22 regex r

假设我有一个像

"Hi,  this is a   good  time to   start working   together.". 
Run Code Online (Sandbox Code Playgroud)

我只想拥有

" Hi, this is a good time to start working together." 
Run Code Online (Sandbox Code Playgroud)

两个单词之间只有一个空格.我应该怎么做R?

the*_*ail 37

gsub 是你的朋友:

test <- "Hi,  this is a   good  time to   start working   together."
gsub("\\s+"," ",test)
#[1] "Hi, this is a good time to start working together."
Run Code Online (Sandbox Code Playgroud)

\\s+将匹配任何空格字符(空格,制表符等),或重复空格字符,并将其替换为单个空格" ".


Koo*_*133 17

另一种选择是 stringr 库中的 squish 函数

library(stringr)
string <- "Hi,  this is a   good  time to   start working   together."
str_squish(string)
#[1] ""Hi, this is a good time to start working together.""
Run Code Online (Sandbox Code Playgroud)

  • 这比其他方法更容易。 (2认同)