Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace one regex match with another and vice versa

Tags:

string

replace

r

I need to replace in string foo bar foo bar bar foo all foo to bar and all bar to foo. So the result should look like bar foo bar foo foo bar.

I have tried this way:

library(stringr)

my_str <- "foo bar foo bar bar foo"
rslt <- str_replace_all(my_str, c("foo", "bar"), c("bar", "foo"))

print(rslt)

but instead I got "bar bar bar bar bar bar" "foo foo foo foo foo foo".

Question: How to correct my code so I get bar foo bar foo foo bar?

like image 824
vasili111 Avatar asked Dec 18 '22 12:12

vasili111


2 Answers

Using str_replace_all multiple replacements and moving the first match to a temporary value.

library(stringr)

str_replace_all(my_str, c("foo" = "tmp", "bar" = "foo", "tmp" = "bar"))

[1] "bar foo bar foo foo bar"
like image 165
manotheshark Avatar answered Jan 09 '23 07:01

manotheshark


No real reason to do this unless you're unable to install extra packages, but just for fun here's a base R solution (following the "tmp" replacement method in @manotheshark's answer):

Reduce(
  function(prev, x) gsub(x[1], x[2], prev),
  list(c('foo', 'tmp'), c('bar', 'foo'), c('tmp', 'bar')),
  my_str)
# [1] "bar foo bar foo foo bar"
like image 22
IceCreamToucan Avatar answered Jan 09 '23 06:01

IceCreamToucan