【问题标题】:stringr: I want to remove stray characters (up to two) flanked by a space on either side [duplicate]stringr:我想删除两侧有空格的杂散字符(最多两个)[重复]
【发布时间】:2021-02-05 17:16:03
【问题描述】:

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

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

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:
    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} ", " ")
    

    【讨论】:

    • 谢谢。这很简单。可能有其他选择,但我很难想到我需要一个不同的解决方案。将在几分钟内接受。
    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 2017-03-01
    • 2020-03-18
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    相关资源
    最近更新 更多