Home > other >  In str_remove: Combine a pattern with a regex in one line
In str_remove: Combine a pattern with a regex in one line

Time:02-24

I have this vector:

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

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

and this not changeable predefined pattern

pattern <- c("abc|xyz")

I would like to combine this two procedures

library(stringr)

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

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

in one line like:

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

Expected output:

[1] "-"    "--12"

My question: is it possible to combine a pattern and a regex in the pattern argument of str_replace

CodePudding user response:

Create a | pattern with sprintf or paste

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

Or another option is file_path_sans_ext on the output from str_remove

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