【问题标题】:Extracting digits after '=' only with negative number仅使用负数提取“=”之后的数字
【发布时间】:2019-05-18 00:57:43
【问题描述】:

我试图仅在“=”字符串之后提取数字

strings <- c("1t clever=120","3c stupid=-150 bad","5k high iq=150 good")

尝试过

as.numeric(gsub("[^\\d]+","",strings,perl = TRUE))

这给了

[1] 1120 3150 5150

预期输出

120 -150 150

我怎样才能得到这个输出?

【问题讨论】:

  • 您的预期输出不仅有非负数。

标签: r regex string extract


【解决方案1】:

我们可以试试

library(stringr)
as.numeric(str_extract(strings, "(?<==)-?\\d+"))
#[1]  120 -150  150

【讨论】:

    【解决方案2】:

    使用基础 R:

    regmatches(strings, gregexpr('(?<==)-?[0-9]+', strings, perl = TRUE))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      相关资源
      最近更新 更多