I am writing R code in Visual Studio Code and would like to replace all words in strings that have the following format:
c("c22lineoftext", "h12another_line_of_text")
to:
c("c22var", "h12var")
I am having some trouble figuring out the correct regex to handle these cases.
What would be the best approach here?
CodePudding user response:
I'm not sure about pattern, but you may try
library(stringr)
x <- c("c22lineoftext", "h12another_line_of_text")
paste0(str_extract(x, "\\w\\d{2}"), "var")
[1] "c22var" "h12var"
CodePudding user response:
Same as @Park with base R:
paste0(sub("(\\w\\d{2}).*", "\\1", x), "var")
[1] "c22var" "h12var"