How to prevent regmatches drop non matches?
use regexec
instead, since it returns a list which will allow you to catch the character(0)
's before unlist
ing
R <- regmatches(x, regexec("a+", x))
unlist({R[sapply(R, length)==0] <- NA; R})
# [1] "a" NA "a" "aa"
Staying with regexpr
:
r <- regexpr("a+", x)
out <- rep(NA,length(x))
out[r!=-1] <- regmatches(x, r)
out
#[1] "a" NA "a" "aa"