Home > OS >  Regex add string after 11th instance of /
Regex add string after 11th instance of /

Time:02-21

I have a collection of web addresses with the following structure:

https://www.example.com/img/public/vendor1/us/en/product-assets/vendor/product/green/device_230x400_a.gif

When constructing this data structure, I realized that I needed to add /image/ after the given product name. The product names will vary, but the slashes are fixed instances, so this should be appropriate: add /image/ after the 11th instance of /.

In other words, aim for:

https://www.example.com/img/public/vendor1/us/en/product-assets/vendor/product/image/green/device_230x400_a.gif

I would greatly appreciate any assistance; I am using Notepad for replacing.

Thanks!

CodePudding user response:

You may use the following find and replace, in regex mode:

Find:    ^(https?://(?:[^/] /){9})(.*)$
Replace: $1image/$2

This regex says to:

^
(                     capture in $1
    https?:           http: or https:
    //                //
    (?:[^\/] \/){9}   match 9 path components
)
(.*)                  capture the remainder of the URL in $2
$

Then we replace with $1image/$2 to insert an /image path component at the desired location.

Here is a demo.

CodePudding user response:

Just replace the match of the regular expression

(?:.*?\/){11}

with $0 'image/'.

Demo

$0 holds the match.

The regular expression can be broken down as follows.

(?:    # begin non-capture group
  .*?  # match zero or more characters, as few as possible (lazily)
  \/   # match '/'
){11}  # end non-capture group and execute it 11 times
  • Related