在 str_remove 中:将模式与正则表达式组合在一行中

In str_remove: Combine a pattern with a regex in one line

我有这个向量:

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"