2

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"
Brad
  • 580
  • 4
  • 19

1 Answers1

2

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563