【发布时间】:2021-02-05 17:16:03
【问题描述】:
我很难使用 stringr 实现以下目标:我想删除两侧有空格的杂散字符(最多两个)。我无法让 stringr 在没有错误的情况下给我很好的结果。下面是两个例子。提前谢谢你。
string1<-'john a smith'
output1<-'john smith'
string2<-'betty ao smith'
output2<-'betty smith'
【问题讨论】:
我很难使用 stringr 实现以下目标:我想删除两侧有空格的杂散字符(最多两个)。我无法让 stringr 在没有错误的情况下给我很好的结果。下面是两个例子。提前谢谢你。
string1<-'john a smith'
output1<-'john smith'
string2<-'betty ao smith'
output2<-'betty smith'
【问题讨论】:
gsub(" \\S{1,2} ", " ", c('john a smith', 'betty ao smith'))
# [1] "john smith" "betty smith"
\\S 是非空格字符{.} 允许重复前面的模式;例如
{2,}至少2个{,3}不超过3个{1,2} 介于 1 和 2 之间stringr 中相同,因为它是“正则表达式”:-)
stringr::str_replace(c('john a smith', 'betty ao smith'), " \\S{1,2} ", " ")
【讨论】: