【问题标题】:Replace white space in string only when there are two or more white spaces仅当有两个或多个空格时才替换字符串中的空格
【发布时间】:2017-02-20 13:10:48
【问题描述】:

我正在处理R 中的字符串。我有下一个字符串:

x<-c("Alfa  Cactus   500   Bachelor degree  Star")

例如,在第一个单词之后的这个字符串中我有两个空格。在第二个单词之后我有三个空格。当有两个或多个空格时,我试图只替换空格。在这种情况下,我想添加 * 而不是空格。我正在寻找这样的新字符串:

Alfa*Cactus*500*Bachelor degree*Star

Bachelor degree 的情况下,我只有一个空格。然后,不得进行更换。当我尝试这个时:

gsub(" +","*",x)

我知道了:

Alfa*Cactus*500*Bachelor*degree*Star

但是,只有一个空格不能被替换这一事实是不尊重的。我不知道如何调整gsub 来执行此更改。

我希望你能帮助我解决这个问题。非常感谢。

【问题讨论】:

    标签: r regex


    【解决方案1】:

    你需要两个空格。

    gsub("  +","*",x)
    [1] "Alfa*Cactus*500*Bachelor degree*Star"
    

    【讨论】:

    • 工作完美!
    猜你喜欢
    • 2012-01-11
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多