Attribute "match.length"
in regexpr
seems to do the job (-1 is used to distinguish match from zero-width matches such as lookaheads)
attr(regexpr(",+$", x), "match.length")
Another option (with input from @JasonAizkalns) would be
nchar(x) - nchar(gsub(",+$", "", x))
Or using the package stringi
in conjunction with nchar
when specifying , keepNA = TRUE
(thus, no matches will be specified as NA
s)
library(stringi)
nchar(stri_extract_all_regex(x, ",+$"), keepNA = TRUE)
## [1] 2 1 NA 3
source
share