【问题标题】:Use gsub to keep only the first part of my string使用 gsub 只保留我的字符串的第一部分
【发布时间】:2017-06-09 09:17:37
【问题描述】:

在 R 中,我的字符串看起来像:

test <- 'ZYG11B|79699'

我只想保留'ZYG11B'

我最好的尝试:

gsub ("|.*$", "", test) # should replace everything after '|' by nothing

但返回

> [1] ""

我该怎么做?

【问题讨论】:

  • 只需转义|,即gsub ("\\|.*$", "", test)

标签: r string gsub


【解决方案1】:

这是一个受保护的字符,这意味着它应该用方括号括起来或用双斜杠转义:

> gsub('[|].*$','', test)
[1] "ZYG11B"
> gsub('\\|.*$','', test)
[1] "ZYG11B"

【讨论】:

    【解决方案2】:

    我们可以的

    library(stringr)
    str_extract(test, "\\w+")
    #[1] "ZYG11B"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2013-03-23
      • 2018-04-23
      • 1970-01-01
      相关资源
      最近更新 更多