Sublime Forum

Find and replace all underscores, but only in image tags

#1

Is there a way to find and replace all underscores with hyphens - in all open files - but only inside an image tag?

For example change

<img src="resources/business_logo.svg" >

to

<img src="resources/business-logo.svg" >

Thank you

0 Likes

#2

I imagine you’d need some sort of script to be able to do that.

Although you could craft a regular expression to match all image tags only and capture the attribute (img\s+src="([^"]*)" for example) and capture the content that’s inside of the src attribute, I don’t think it’s possible to manipulate the captured attribute text as it’s being replaced.

0 Likes

#3

Okay. Thank you

0 Likes

#4

Find and replace with the following after turning on regular expressions and turning off the “whole word” option:

find: (?<=<img src=")(.*)_(.*" >)
repl: \1-\2

There is a quirk with this which I’m going to call a bug in ST: if you repeatedly do a Replace with this it will replace multiple underscores inside one tag and eventually finish all of them in the file. If you do a Replace All it will only do one per tag and you have to repeatedly do a Replace All to get them all. Try it and you’ll see what I mean.

0 Likes

#5

Urm, it can’t find any matches. Am I doing this right?
32%20am

0 Likes

#6

The regex is given for exactly the data you posted. If the spacing is different you’ll need to change it. This version will work with any spacing between " and > but ‘<img src=’ must still match exactly:

find: (?<=<img src=")(.*)_(.*"\s*>)
repl: \1-\2

You can change ‘’, ‘_’ and ‘-’ to almost anything and it will work. \s* matches zero or more spaces.

Also try it with a single window search to make sure it works properly before doing open files and folders.

Finally if you copy and pasted the regex from the web page it sometimes puts in weird space characters when you paste, so if it still doesn’t work delete each space in the find field and retype it.

Edit: Added missing double quote in third paragraph.

0 Likes

#7

note that this only replaces the first ‘_’ inside an image tag.

0 Likes

#8

I’m going to have to do this manually. i think this is the only way to do it

The provided solution only changes the last underscore in a file name:
photo_name_wildlife-image.jpg

0 Likes

#9

As I said in my first post there is a bug in ST that makes Replace All only do one replacement per tag. The work around is to repeatedly do Replace All until they’re all done.

0 Likes

#10

You’re probably better of writing a derived parser: https://docs.python.org/3/library/html.parser.html
This will guarantee you’re actually in an img tag and you won’t have to worry if your regex is correct.

0 Likes