我正在尝试从长字符串中的向量中找到第一个匹配的字符串。例如,我有一个 example_string <- 'LionabcdBear1231DogextKittyisananimalTurtleisslow'
和一个 matching_vector<- c('Turtle',Dog')
现在我希望它返回“Dog”,因为这是我们在示例字符串中看到的匹配向量中的第一个子字符串:LionabcdBear1231DogextKittyisananimalTurtleisslow
我已经尝试过pmatch(example_string,matching_vector)
但它不起作用。显然,因为它不适用于子字符串...
谢谢! 蒂姆
最佳答案
以下解决方案适合您吗?
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"
关于r - 在 R 中查找长字符串中的第一个匹配子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40347051/