We can use sub
to capture the digits as a group from the start (^
) of the string followed by the -
, then capture the two digits ((\d{2})
) and replace with the backreference (\1\2
) of the captured group
f1 <- function(nm) as.numeric(sub("^(\d+)-(\d{2}).*", "\1\2", nm))
f1(str1)
#[1] 2018
data
str1 <- "20-1843PA-HY-4563-214DF"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…