Another interpretation:
s <- "abs" # Updated vc vc <- c("ab","bb","abc","acbd","dert","abwabsabs") st <- strsplit(s, "")[[1]] mtc <- sapply(strsplit(substr(vc, 1, nchar(s)), ""), function(i) { m <- i == st[1:length(i)] sum(m * cumsum(m))}) vc[mtc == max(mtc)] #[1] "ab" "abc" "abwabsabs" # Another vector vc vc <- c("ab","bb","abc","acbd","dert","absq","abab") .... vc[mtc == max(mtc)] #[1] "absq"
Since we consider only the beginning of lines, in the first case the greatest match was "ab" , although there is "abwabsabs" that has "abs" .
Edit: Here is a βone templateβ solution, maybe it can be more concise, but here we go ...
vc <- c("ab","bb","abc","acbd","dert","abwabsabs") (auxOne <- sapply((nchar(s)-1):1, function(i) substr(s, 1, i))) #[1] "ab" "a" (auxTwo <- sapply(nchar(s):2, function(i) substring(s, i))) #[1] "s" "bs" l <- attr(regexpr( paste0("^((",s,")|",paste0("(",auxOne,"(?!",auxTwo,"))",collapse="|"),")"), vc, perl = TRUE), "match.length") vc[l == max(l)] #[1] "ab" "abc" "abwabsabs"