我有这个向量:
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
的模式参数中组合模式和正则表达式
最佳答案
使用 sprintf
或 paste
创建 |
模式
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/