Find common substrings between two character variables

lcs, r

Solution

Here's a CRAN package for that:

library(qualV)

sapply(seq_along(a), function(i)
    paste(LCS(strsplit(a[i], '')[[1]], strsplit(b[i], '')[[1]])$LCS,
          collapse = ""))

Problem

I have two character variables (names of objects) and I want to extract the largest common substring. ``` a <- c('blahABCfoo', 'blahDEFfoo') b <- c('XXABC-123', 'XXDEF-123') ``` I want the following as a result: ``` [1] "ABC" "DEF" ``` These vectors as input should give the same result: ``` a <- c('textABCxx', 'textDEFxx') b <- c('zzABCblah', 'zzDEFblah') ``` These examples are representative. The strings contain identifying elements, and the remainder of the text in each vector element is common, but unknown. Is there a solution, in one of the following places (in order of preference): Base R Recommended Packages Packages available on CRAN The answer to the supposed-duplicate does not fulfill these requirements.

Original source

Related problems