Tim_Utrecht Tim_Utrecht - 9 months ago 59
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
but it doesn't work. Obviously as it doesn't work with substrings...


Answer Source

We can use stri_match_first from stringi

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