【问题标题】:Extract first number from string从字符串中提取第一个数字
【发布时间】:2012-12-22 14:16:46
【问题描述】:

我有一个字符串 thisLine,它包含 11 个用空格分隔的数字。我只想获得第一个数字。我尝试了命令:

grep('\\d*\\.\\d*',thisLine,value=TRUE)

它返回整个字符串,而不是第一个数字。如何只返回第一个数字?

【问题讨论】:

    标签: regex r


    【解决方案1】:

    我相信有很多可能性,我会考虑以下几种:

    thisLine <- paste(runif(11), collapse = " ")
    thisLine
    # [1] "0.841216114815325 0.861485596280545 0.973681036382914 0.683699210174382 0.95226536039263 0.368689567316324 0.173984130611643 0.497511914698407 0.870743532432243 0.45606177020818 0.222731305286288"
    
    sub("\\s+.*", "", thisLine)              # assumes no leading space
    sub("\\s*(\\S+?)\\s.*", "\\1", thisLine) # handles leading spaces
    strsplit(thisLine, " ")[[1]][1]          # more flexible if you want 2nd, 3rd, ...
    

    全部给予

    # [1] "0.841216114815325"
    

    【讨论】:

    • 谢谢!我最终使用了 strsplit。
    【解决方案2】:

    您可以使用 strex 包中的 str_first_number() 函数很好地做到这一点。

    library(strex)
    johnsmith <- "John Smith, 34 years of age, 6ft tall, 85kg."
    str_first_number(johnsmith)
    #> [1] 34
    str_nth_number(johnsmith, n = 1)  # first number
    #> [1] 34
    str_nth_number(johnsmith, n = 2)  # second number
    #> [1] 6
    str_nth_number(johnsmith, n = -1)  # last number
    #> [1] 85
    str_last_number(johnsmith)
    #> [1] 85
    

    reprex package (v0.2.0) 于 2018 年 9 月 3 日创建。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-12
      • 2022-11-02
      • 2015-02-08
      • 2020-02-12
      • 1970-01-01
      • 2018-06-27
      相关资源
      最近更新 更多