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

时间:2012-04-18 17:56:59

标签: regex r grep

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

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

返回

[1] "Ref. 13" "Ref. 14"

所以我失去了Ref。 12.

4 个答案:

答案 0 :(得分: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+))"))

答案 1 :(得分:6)

怎么样

sapply(data,stringr::str_extract_all,pattern="Ref. (\\d+))")

答案 2 :(得分:4)

这是一个函数 - 本质上是gregexpr()的包装器 - 它将从单个字符串中捕获多个引用。

extractMatches <- function(data, pattern) {
    start <-  gregexpr(pattern, data)[[1]]
    stop  <-  start + attr(start, "match.length") - 1
    if(-1 %in% start) {
        ""    ## **Note** you could return NULL if there are no matches 
    } else {
        mapply(substr, start, stop, MoreArgs = list(x = data))
    }
}    

data <- list("a sentence with citation (Ref. 12), (Ref. 13), and then (Ref. 14)",
             "another sentence without reference")
pat <- "Ref. (\\d+)"

res <- lapply(data, extractMatches, pattern = pat)
res
# [[1]]
# [1] "Ref. 12" "Ref. 13" "Ref. 14"
# 
# [[2]]
# [1] ""

(**注意**:如果在字符串中没有引用时返回NULL而不是"",那么您可以使用do.call("c", res)对结果进行后处理以获取一个只包含匹配参考的矢量。)

答案 3 :(得分:2)

我之前遇到了一个非常类似的问题(http://thebiobucket.blogspot.com/2012/03/how-to-extract-citation-from-body-of.html),并提出了这个问题(实际上非​​常接近本的)解决方案:

require(stringr)
unlist(str_extract_all(unlist(data), pattern = "\\(.*?\\)"))

,并提供:

[1] "(Ref. 12)" "(Ref. 13)" "(Ref. 14)"