r - 在 R 中查找长字符串中的第一个匹配子字符串

标签 r regex string

我正在尝试从长字符串中的向量中找到第一个匹配的字符串。例如,我有一个 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/

相关文章:

r - R 代码中 pivot_longer 函数的问题

正则表达式 - 将文件重命名为文件名中的最高分辨率

python - 使用 numpy.char 函数需要哪些 numpy 结构作为输入?

java - java从文本文件中的特定位置获取单词

python - 拆分长字符串而不中断单词填充行

java - 将字符串(时间戳)转换为整数

r - 使用二进制值时 R 中的直方图

r - 在 R 中,如何检查卸载包中是否存在函数?

r - Shiny 的多重动态子集

java - 如何在正则表达式中发现 *?