The stringi package has convenient functions that work with certain parts of the string. So you can find the last occurrence of four consecutive digits with the following.
library(stringi) x <- c("2005-", "2003-", "1984-1992, 1996-") stri_extract_last_regex(x, "\\d{4}") # [1] "2005" "2003" "1996"
Other ways to get the same result:
stri_sub(x, stri_locate_last_regex(x, "\\d{4}")) # [1] "2005" "2003" "1996" ## or, since these count as words stri_extract_last_words(x) # [1] "2005" "2003" "1996" ## or if you prefer a matrix result stri_match_last_regex(x, "\\d{4}") # [,1] # [1,] "2005" # [2,] "2003" # [3,] "1996"
source share