Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gsub to return all matches of an expression instead of just the last match

Tags:

regex

r

I'm looking for a gsub string that will return all matches of an expression, rather than just the last match. i.e.:

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

Returns

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

so I've lost Ref. 12.

like image 759
cboettig Avatar asked Dec 01 '22 00:12

cboettig


1 Answers

You can use the strapply function from the gsubfn package to do this:

library(gsubfn)

data <- list("a sentence with citation (Ref. 12) and another (Ref. 13)", "single (Ref. 14)") 
unlist(strapply(data,"(Ref. (\\d+))"))
like image 94
Greg Snow Avatar answered Dec 03 '22 23:12

Greg Snow