Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading