【发布时间】:2013-10-08 07:54:36
【问题描述】:
假设我有一个像
这样的字符向量"Hi, this is a good time to start working together.".
我只想拥有
" Hi, this is a good time to start working together."
两个单词之间只有一个空格。我应该如何在 R 中做到这一点?
【问题讨论】:
假设我有一个像
这样的字符向量"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+ 将匹配任何空格字符(空格、制表符等)或空格字符的重复,并将其替换为单个空格 " "。
【讨论】:
"\\s" 而不是" ",谢谢!
"\\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")
请参阅regex demo #1 和 regex demo #2 和 this R demo。
正则表达式详细信息:
(\S) - 捕获组 1(\1 指替换模式中的该组值):非空白字符\s{2,} - 两个或更多空白字符(在 Regex #2 中,它用括号括起来以形成 ID 为 2 (\2) 的捕获组)(?=\S) - 正向前瞻,需要在当前位置右侧紧邻非空白字符。【讨论】: