rstring-matchingfuzzy-search

Extract near matches from longer string


I'm trying to extract near matches from a string, where the pattern is misspelled. Looking for the phrase "Se abre la sesión"

Here's a reproducible example.

pattern <- "Se abre la sesión"

text <- "Al ingresar a la aplicación, el usuario debe proporcionar sus credenciales de acceso. Si las credenciales son correctas, se abra la sesión y el usuario puede empezar a utilizar la aplicación."

I've tried this:

matches <- agrepl("Se abre la sesión", text, ignore.case = TRUE, max.distance = 3)
spelling <- str_extract(text[matches], "Se abre la sesión")

and this:

library(stringdist)
matches <- which(stringdist(text, "Se abre la sesión", method = "lv", useBytes = TRUE) <= 3)
match_text <- substr(text, matches, matches + nchar("Se abre la sesión") - 1)

Solution

  • Use aregexec with regmatches to extract near matches from a string.

    regmatches(text,
        aregexec("Se abre la sesión", text, ignore.case = TRUE, max.distance = 3))
    #[[1]]
    #[1] "se abra la sesión"