How to swap substring in a string?

Advertisements

Let’s assume I have the following string:

x <-  "22-03-23"

Given this and given any other similar string with the same format I want to be able to swap the position of "22" with "23" in an automated way.

Hence, result should be:

"23-03-22"

The code needs to abstract from those numbers and work in any other scenario with the same format.

Can anyone help me with this?

>Solution :

You can do:

x <- c("22-03-23", "01-04-20")
gsub("(.*)(-.*-)(.*)", "\\3\\2\\1", x)
#[1] "23-03-22" "20-04-01"

Leave a ReplyCancel reply