假设我有一个像
"Hi, this is a good time to start working together.".
我只想拥有
" Hi, this is a good time to start working together."
两个单词之间只有一个空格。我应该如何在 R 中做到这一点?
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+
将匹配任何空格字符(空格、制表符等)或空格字符的重复,并将其替换为单个空格" "
。
另一个选项是 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.""
由于问题的标题是“删除单词之间的多余空格”,而不触及前导和尾随空格,答案是(假设“单词”是非空白字符块)
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)
- 一个正向前瞻,需要在当前位置的右侧立即有一个非空白字符。