-2

I'm using the latest version of Sublime text and I would like to Find & Replace a variable value in my list of URLs.

So an example of the URLs in the list is;

root/tesco-loves-baby-bath-and-room-thermometer_w227_h218.jpg

and

toddler-lunch-ideas-dairy-free_w555_h555.jpg

And I need to replace this URL with;

.jpg?q=80&auto=format&w=1800&ar=16:9&fit=crop&crop=top

However, instead of the w=1800 in this replacement, I need to extract out the _w value of the original URL, and use this in the new URL.

So the

_w227_h218.jpg

part of the original URL would be replaced with;

.jpg?q=80&auto=format&w=227&ar=16:9&fit=crop&crop=top

And

_w555_h555.jpg

would be replaced with;

.jpg?q=80&auto=format&w=555&ar=16:9&fit=crop&crop=top

etc.

Is this possible in Sublime text?

Or is there another way of doing this?

I did think of trying to use regex, but my experience of using regex is very limited so thought I'd give this a go first.

Thanks

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Darren Harley
  • 75
  • 1
  • 18

1 Answers1

-1

This is actually quite straightforward to do. In Sublime, select Find → Replace…. Make sure the Regular Expression option is selected. In the Find: box, enter:

_w(\d+)_h\d+.jpg

The parentheses () indicate a capturing group. \d+ searches for one or more digits.

Now, in the Replace: box, enter this:

\.jpg?q=80&auto=format&w=$1&ar=16:9&fit=crop&crop=top

The $1 means insert first capture group here. Hit the Replace button a few times to make sure your URLs are being changed properly. Once you're satisfied it works, you can hit Replace All to make the changes all at once.

I've put a demo on regex101 so you can see the exact breakdown of what's going on.

MattDMo
  • 100,794
  • 21
  • 241
  • 231