首页 > 解决方案 > 用字典中的第一个匹配替换字符串

问题描述

我有一个向量long_strings定义为

long_strings <- c("*/1/1/1/1", "*/1/2/1/1", "*/2/1",
                "*/2/2/1", "*/3/1/1/1")

我有一个简短的字典,short_strings其中包含这些字符串的初始模式(具有不同的长度),例如

short_strings <- c("*/1/1", "*/3", "*/2", "*/1/2")

如何“简化” 的内容long_strings以匹配其对应的值short_strings

结果应该看起来像

"*/1/1", "*/1/2", "*/2", "*/2", "*/3"

short_strings我可以找到using的单个元素出现在哪里grep("\\*/2", long_strings),但我想避免在short_strings.

标签: rregexstring

解决方案


一个选项sapply

as.character(with(stack(sapply(setNames(paste0("\\", short_strings), short_strings),
     grep, x = long_strings)), ind[order(values)]))
#[1] "*/1/1" "*/1/2" "*/2"   "*/2"   "*/3" 

或使用str_extract

library(stringr)
str_extract(long_strings, str_c(str_c("\\", short_strings), collapse="|"))
#[1] "*/1/1" "*/1/2" "*/2"   "*/2"   "*/3"   

推荐阅读