gsub返回表达式的所有匹配而不是最后一个匹配

cbo*_*tig 4 regex grep r

我正在寻找一个gsub字符串,它将返回表达式的所有匹配,而不仅仅是最后一个匹配.即:

data <- list("a sentence with citation (Ref. 12) and another (Ref. 13)", "single (Ref. 14)")
gsub(".*(Ref. (\\d+)).*", "\\1", data)
Run Code Online (Sandbox Code Playgroud)

返回

[1] "Ref. 13" "Ref. 14"
Run Code Online (Sandbox Code Playgroud)

所以我失去了Ref.12.

Gre*_*now 7

您可以使用包中的strapply函数gsubfn执行此操作:

library(gsubfn)

data <- list("a sentence with citation (Ref. 12) and another (Ref. 13)", "single (Ref. 14)") 
unlist(strapply(data,"(Ref. (\\d+))"))
Run Code Online (Sandbox Code Playgroud)


Ben*_*ker 6

怎么样

sapply(data,stringr::str_extract_all,pattern="Ref. (\\d+))")
Run Code Online (Sandbox Code Playgroud)