Home > Back-end >  How to use str_replace_all with conflicting values
How to use str_replace_all with conflicting values

Time:07-25

Example: I have a string containing one and two and I would like to change it to two and one. Is there a way to do this with str_replace (or str_replace_all)?

CodePudding user response:

Base R option using gsub which swaps the words before and after " and " like this:

string <- "one and two"
gsub("(.*) and (.*)", "\\2 and \\1", string)
#> [1] "two and one"

Created on 2022-07-25 by the reprex package (v2.0.1)

CodePudding user response:

Using stringr

library(stringr)

str="one and two"
str_c(rev(str_split(str, " ")[[1]]), collapse=" ")
[1] "two and one"

CodePudding user response:

We can use str_replace with capture groups:

x <- "one and two"
output <- str_replace(x, "(\\w ) and (\\w )", "\\2 and \\1")
output

[1] "two and one"
  • Related