Home > Software design >  Regex, substitute part of a string always at the end
Regex, substitute part of a string always at the end

Time:06-07

I am trying to substitute a string so a part of this url always goes to the end

google.com/to_the_end/faa/
google.com/to_the_end/faa/fee/
google.com/to_the_end/faa/fee/fii

Using this

(google\.com)\/(to_the_end)\/([a-zA-Z0-9._-] )

$1/$3/$2

It works for the first example, but I need something a bit more versatile so no matter how many folders it always moves to_the_end as the last folder in the url string

Desired output

google.com/faa/to_the_end
google.com/faa/fee/to_the_end/
google.com/faa/fee/fii/to_the_end/

CodePudding user response:

You can use

(google\.com)\/(to_the_end)\/(.*[^\/])\/?$

See the regex demo.

Details:

  • (google\.com) - Group 1: google.com
  • \/ - a / char
  • (to_the_end) - Group 2: to_the_end
  • \/ - a / char
  • (.*[^\/]) - Group 3: any zero or more chars other than line break chars as many as possible and then a char other than a / char
  • \/? - an optional / char
  • $ - end of string.
  • Related