r - 用字典中的第一个匹配替换字符串
问题描述
我有一个向量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
.
解决方案
一个选项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"
推荐阅读
- javascript - “QuerySnapshot”类型上不存在属性“docs”
[]' - python - 是否可以从 Manim 动画视频中以 png 格式导出图片?
- docker - 如何将 docker app 部署到离线服务器
- terraform - 由较新的提供程序版本错误管理的资源实例
- jenkins - 中止 Jenkins 流水线阶段而不中止后续阶段
- c - 为什么当前节点中的int字段与链表中下一个节点的字符串字段相同?
- visual-studio-2019 - 在新的 VS2019 中,解决方案资源管理器中的“定位当前文件”按钮在哪里?
- reactjs - 如何使用 Webpack 并模拟或替换特定模块?
- javascript - 将位置移动到滚动条上的特定元素(类)
- angular - 如何将数据从模板发送到 Angular 中包含的组件?