Suffix to prefix and prefix to suffix in R

Viewed 320

I have a string.

String <- "like_a_butterfly_sting_like_a_bee_Float"

I can make the first prefix become the last suffix by pivoting on the first underscore.

gsub("^([^_]*)_(.*)$", "\\2_\\1",String)

How can I make the final suffix become the first prefix by pivoting on the last underscore?

Desired result: "Float_like_a_butterfly_sting_like_a_bee"
1 Answers

You may swap the patterns in the first and second capturing group:

sub("^(.*)_([^_]*)$", "\\2_\\1",String)

See the regex demo

Details

  • ^ - start of string
  • (.*) - Capturing group 1: any zero or more chars as many as possible
  • _ - a _ char
  • ([^_]*) - Capturing group 2: zero or more chars other than _
  • $ - end of string
Related