Tim_Utrecht
Tim_Utrecht

Reputation: 1519

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

Upvotes: 2

Views: 224

Answers (2)

akrun
akrun

Reputation: 887078

We can use stri_match_first from stringi

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

Upvotes: 1

Tobias Dekker
Tobias Dekker

Reputation: 1030

Is the following solution working for you?

example_string <- 'LionabcdBear1231DogextKittyisananimalTurtleisslow'
matching_vector<- c('Turtle','Dog')
match_ids <- sapply(matching_vector, function(x) regexpr(x ,example_string)) 
result <- names(match_ids)[which.min(match_ids)]
> result
[1] "Dog"

Upvotes: 2

Related Questions