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

How to swap substring in a string?

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:

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

"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"
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