【问题标题】:R: extracting numbers from string [duplicate]R:从字符串中提取数字[重复]
【发布时间】:2017-02-17 09:54:54
【问题描述】:

我正在尝试使用 R 中的包 stringi 从字符串中提取数字。字符串的模式是:

1 nomination
2 wins
1 win & 3 nominations
2 wins & 1 nomination
won 1 Oscar. Another 5 wins & 2 nominations

我希望提取每个字符串中的数字。如果只有 win 或 nomination,则将唯一的数字视为获胜/提名。

到目前为止,我已经尝试了以下方法:

test <- "6 wins & 3 nominations."

str_extract(test, regex="\\w*\\d\\w*")

但是,这只给出了第一个数字,不包括第二个数字。

stri_extract(test, regex="\\w*\\d+wins(\\s*+&amp;+\\s*)(\\d)") 给出不适用。

以下方式可行,但感觉太笨拙,先拆分字符串,然后是 stri_extract:

t <- strsplit(test, "&")  # split the string first
win_num <- stri_extract(t[1], regex="\\d")
nomination_num <- stri_extract(t[2], regex="\\d") # if exists

有什么方法可以让正则表达式在一行中工作?谢谢!

【问题讨论】:

    标签: r regex extract


    【解决方案1】:

    要提取多个数字,请使用str_extract_all,它会返回list 输出。

    str_extract_all(test, "\\d+")[[1]]
    

    【讨论】:

    • 其实是stri_extract_all(test, regex="\\d+")[[1]],谢谢!
    • @TonyGW 是的,我没有指定regex=,但不指定它就可以工作。
    猜你喜欢
    • 2017-12-30
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2020-11-02
    • 1970-01-01
    • 2020-04-22
    相关资源
    最近更新 更多