r - 在str_remove : Combine a pattern with a regex in one line中

标签 r vector stringr

我有这个向量:

vec <- c("abc-xyz.png", "abc-xyz-12.jpg")

[1] "abc-xyz.png"    "abc-xyz-12.jpg"

这个不可更改的预定义模式

pattern <- c("abc|xyz")

我想结合这两个过程

library(stringr)

str_remove_all(vec, pattern)
[1] "-.png"    "--12.jpg"

str_remove_all(vec, '\\..*')
[1] "abc-xyz"    "abc-xyz-12"

一行如:

str_remove_all(vec, pattern & '\\..*') # does not work

预期输出:

[1] "-"    "--12"

我的问题:是否可以在 str_replace 的模式参数中组合模式和正则表达式

最佳答案

使用 sprintfpaste 创建 | 模式

stringr::str_remove_all(vec, sprintf("%s|\\..*", pattern))
[1] "-"    "--12"

或者另一个选项是 str_remove 输出上的 file_path_sans_ext

tools::file_path_sans_ext(stringr::str_remove_all(vec, pattern))
[1] "-"    "--12"

关于r - 在str_remove : Combine a pattern with a regex in one line中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71243061/

相关文章:

r - 直方图 x 轴显示错误范围

r - 一个图中的多个维恩图 R

r - 根据大型数据集中的平均值分配通过/失败值

r - str_replace_all 不在管道中工作

r - 在 R 中将数字添加到字母数字字符串的有效方法

r - 如何返回一列的行值,使得它们在另一列中的对应值是R中最小的n值

c++ - 为 vector 实例化一个模板

c++ - 二维 vector 类型转换

c++ - std::vector 无法解释的行为

r - 在第一个以大写字母开头的单词后添加逗号