首页 > 解决方案 > stringr:我想删除两侧有空格的杂散字符(最多两个)

问题描述

我很难用 stringr 实现以下目标:我想删除两侧有空格的杂散字符(最多两个)。我无法让 stringr 在没有错误的情况下给我很好的结果。下面是两个例子。先感谢您。

string1<-'john a smith'
output1<-'john smith'
string2<-'betty ao smith'
output2<-'betty smith'

标签: rregexstringr

解决方案


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} ", " ")

推荐阅读