我正在尝试使用stringi
R中的包从字符串中提取数字。字符串的模式为:
1 nomination
2 wins
1 win & 3 nominations
2 wins & 1 nomination
won 1 Oscar. Another 5 wins & 2 nominations
我希望提取每个字符串中的数字。如果只有获胜或提名,则将唯一号码视为获胜/提名。
到目前为止,我已经尝试了以下方法:
test <- "6 wins & 3 nominations."
str_extract(test, regex="\\w*\\d\\w*")
但是,这仅给出第一个数字,不包括第二个数字。
stri_extract(test, regex="\\w*\\d+wins(\\s*+&+\\s*)(\\d)")
给出NA。
可以使用以下方法,但是先分割字符串,再分割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
有什么办法可以使正则表达式在一行中起作用?谢谢!
要提取多个数字,请使用str_extract_all
,以返回list
输出。
str_extract_all(test, "\\d+")[[1]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句