stringr:我想删除两侧有 space 的杂散字符(最多两个)

stringr: I want to remove stray characters (up to two) flanked by a space on either side

我很难用 stringr 实现以下目标:我想删除两边有 space 的杂散字符(最多两个)。我无法让 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 是非space 字符
  • {.} 允许重复前面的模式;例如
    • {2,} 至少 2
    • {,3}不超过3
    • {1,2} 在 1 和 2 之间

stringr 相同,因为它“只是正则表达式”:-)

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