【问题标题】:Is there an R function to extract all numbers followed by specific pattern?是否有一个 R 函数来提取所有数字,然后是特定模式?
【发布时间】:2019-08-21 00:35:54
【问题描述】:

我正在使用 R。我想提取向量中最后一个空格和字符串模式(“-APPLE”)之间的所有数字。这些数字可以是可变长度的。

test_string = c("ABC 2-APPLE", "123 25-APPLE", "DEF GHI 567-APPLE", "ORANGE")

预期结果集应该是一个向量,如 c(2, 25, 567, NA)

【问题讨论】:

    标签: r string extraction


    【解决方案1】:

    请参阅Regex group capture in R with multiple capture-groups,了解使用str_match() 的示例,来自stringr 包。

    在你的情况下:

    > test_string = c("ABC 2-APPLE", "123 25-APPLE", "DEF GHI 567-APPLE")
    > 
    > library(stringr)
    > x <- str_match(test_string, " ([0-9]+)-APPLE$")[,2]
    > as.numeric(x)
    [1]   2  25 567
    

    【讨论】:

    【解决方案2】:

    您可以使用“rebus”包,它在创建您需要的正则表达式模式时非常用户友好。

    library(rebus)
    ## adjust the lo and hi arguments of dgt() based on your text
    
    rx <- lookbehind(SPACE) %R% dgt(1,5) %R% lookahead("-APPLE")
    str_extract(test_string, rx)
    

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 2021-07-28
      相关资源
      最近更新 更多