【问题标题】:Remove first occurrence of underscore in a string删除字符串中第一次出现的下划线
【发布时间】:2016-08-09 05:48:38
【问题描述】:

我有一个字符串,看起来像

"_6302_I-PAL_SPSY_000237_001"

我需要删除第一个出现的下划线,这样它就会像

"6302_I-PAL_SPSY_000237_001"

我知道gsub,但它删除了所有下划线。感谢您的任何建议。

【问题讨论】:

  • 您要删除第一次出现的下划线还是删除第一个字符下划线?

标签: r


【解决方案1】:

gsub 函数做同样的事情,删除字符串符号 ^ 的开头使用

    x <- "_6302_I-PAL_SPSY_000237_001"

    x <- gsub("^\\_","",x)

    [1] "6302_I-PAL_SPSY_000237_001"

【讨论】:

  • 为什么使用“\\”。看来gsub("^_","",x)就够了。
【解决方案2】:

我们可以使用sub,模式为_,替换为空白("")。这将删除第一次出现的“_”。

sub("_", "", str1)
#[1] "6302_I-PAL_SPSY_000237_001"

注意:这将删除 _first 出现,并且不会根据位置进行限制,即字符串的 start

例如,假设我们有字符串

str2 <- "6302_I-PAL_SPSY_000237_001"
sub("_", "", str2)
#[1] "6302I-PAL_SPSY_000237_001"

由于示例开头有_,另一个选项是substring

substring(str1, 2)
#[1] "6302_I-PAL_SPSY_000237_001"

数据

str1 <- "_6302_I-PAL_SPSY_000237_001"

【讨论】:

    【解决方案3】:

    这也可以使用 base R 的 trimws() 来完成

    string1<-"_6302_I-PAL_SPSY_000237_001"
    
    trimws(string1, which='left', whitespace = '_')
    
    [1] "6302_I-PAL_SPSY_000237_001"
    

    如果我们有多个带有前导下划线的单词,我们可能必须在正则表达式中包含单词边界 (\\b),并使用 gsub 或 stringr::string_remove

    string2<-paste(string1, string1)
    
    string2
    [1] "_6302_I-PAL_SPSY_000237_001 _6302_I-PAL_SPSY_000237_001"
    
    library(stringr)
    
    str_remove_all(string2, "\\b_")
    > str_remove_all(string2, "\\b_")
    
    [1] "6302_I-PAL_SPSY_000237_001 6302_I-PAL_SPSY_000237_001"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 2017-07-07
      相关资源
      最近更新 更多