r语言 - 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}between 1 and 2

stringr相同,因为它只是": -)

stringr::str_replace(c('john a smith', 'betty ao smith'), " \S{1,2} ", " ")

最新更新