33

假设我有一个像

"Hi,  this is a   good  time to   start working   together.". 

我只想拥有

" Hi, this is a good time to start working together." 

两个单词之间只有一个空格。我应该如何在 R 中做到这一点?

4

3 回答 3

53

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."

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

于 2013-10-02T00:56:03.713 回答
21

另一个选项是 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.""
于 2019-10-01T13:36:28.830 回答
3

由于问题的标题是“删除单词之间的多余空格”,而不触及前导和尾随空格,答案是(假设“单词”是非空白字符块)

gsub("(\\S)\\s{2,}(?=\\S)", "\\1 ", text, perl=TRUE)
stringr::str_replace_all(text, "(\\S)\\s{2,}(?=\\S)", "\\1 ")
## Or, if the whitespace to leep is  the last whitespace in those matched
gsub("(\\S)(\\s){2,}(?=\\S)", "\\1\\2", text, perl=TRUE)
stringr::str_replace_all(text, "(\\S)(\\s){2,}(?=\\S)", "\\1\\2")

请参阅正则表达式演示 #1正则表达式演示 #2以及此 R 演示

正则表达式详细信息

  • (\S)- 捕获组 1(\1指替换模式中的该组值):非空白字符
  • \s{2,}- 两个或多个空白字符(在 Regex #2 中,它用括号括起来以形成 ID 为 2 ( \2) 的捕获组)
  • (?=\S)- 一个正向前瞻,需要在当前位置的右侧立即有一个非空白字符。
于 2021-03-06T12:25:27.070 回答