Tim_Utrecht Tim_Utrecht - 1 month ago 13
R Question

Find first matching substring in a long string in R

I'm trying to find the first matching string from a vector in a long string. I have for example a

example_string <- 'LionabcdBear1231DogextKittyisananimalTurtleisslow'
and a
matching_vector<- c('Turtle',Dog')
Now I want that it returns 'Dog' as this is the first substring in the matching_vector that we see in the example string: LionabcdBear1231DogextKittyisananimalTurtleisslow

I already tried
pmatch(example_string,matching_vector)
but it doesn't work. Obviously as it doesn't work with substrings...

Thanks!
Tim

Answer

We can use stri_match_first from stringi

library(stringi)
stri_match_first(example_string, regex = paste(matching_vector, collapse="|"))