Extract strings using fuzzy LR patterns in R

Viewed 72

I am struggling for long time.

I manage to extract everything between my Right and Left patterns in a string as you can see in the following example.

library(tidyverse)

data=c("everything will be ok one day")

str_extract(string = data, pattern = "(?<=thing).*(?=ok one)")
#> [1] " will be "

Created on 2022-01-26 by the reprex package (v2.0.1)

As you notice in the code, I extract everything between "thing" and "ok one".

I need to incorporate the possibility of mismatches inside these patterns. I want to allow a maximum of two mismatches and consider indels and insertions.


Example1

for example one mismatch that I want to account for is the insertion of letter "s" in everything

dat.1=c("everythings will be ok one day")

I would like in this case to be able to extract the the phrase

will be 

Example 2

dat.2=c("everythingswillbeokoneday")

I would like in this case to be able to extract the the phrase

will be 

PS: This is just a simplified example. My actual data does not contain gaps, and it's complicated. I am looking forward to receiving your help and guidance.

1 Answers

One way is to use fuzzy matching of strings, relying, for instance, on package stringdist and computing, for each delimiter string (thing and ok, in your example), the respective matching score (that is what the function maxsim does below).

library(tidyverse)
library(stringdist)

dat.1=c("everythings will be ok one day")

maxsim <- function(df, delim)
{
  df %>% 
    str_split(" ") %>% unlist %>% 
    map(~ stringsim(delim,.x)) %>% 
    which.max
} 

dat.1 %>% 
  str_split(" ") %>% unlist %>% 
  .[ (maxsim(dat.1,"thing") + 1) : (maxsim(dat.1,"ok") - 1) ] %>% 
  str_c(collapse = " ")

#> [1] "will be"
Related