Changing regexes to target image links - regex

I need to batch change a folder full of files, changing all image links to lower case and replacing underscores with dashes. Thus, <img src="/images/Maps/South_America.png"> would become <img src="images/maps/south-america.png">
I already performed similar operations on all local links in the same files. I used this regex to change them to lower case:
(?<=(?i)href=")((?:<\?php(?:(?!\?>).)+\?>)?)((?:'[^']+')?)([^"]+)(?=")
\1\2\L\3
And I used this one to replace underscores with dashes:
(href="(?!http)[^_"]+)\_([^"]+")
$1-$2
I'm not even sure if they're the same "language;" I think one only works in Dreamweaver, the other in TextWrangler. Anyway, I haven't figured out how to modify to match images, rather than links. I should emphasize that I only to change the image paths and names, not any classes, ID's or alt tags.
For example, <img src="Buffalo_Bill.jpg" alt="Buffalo Bill" class="People"> would become <img src="buffalo-bill.jpg" alt="Buffalo Bill" class="People">
Also, I think this covers all the bases if defining image extensions is necessary...
(?:jpe?g|gif|png|svg|swf)
The regexes I posted above are just examples. If you have a regex that's totally different, that's fine - just as long as it will work in a common text editor like Dreamweaver or TextWrangler. (I'm on a Mac.)

With an input like this:
<img id="BoringSnowDay" class="FunkySmellsFromGarden" src="/images/Maps/South_America.png" alt="Powerball Winner!" /> <img id="ExcitingSunNight" class="SmoothTasteInKitchen" src="/images/Flags/Antartica.jpg" alt="Racecar racecaR!" />
This regex in TextWrangler:
(<img [^>]+)(src="[^"]+")
Replace:
\1\L\2
Gives me something that ONLY affects the src="..." portion and nothing else.
Unfortunately, combining that to a "...and replace _ to -" tends to get a little tricky.

Related

Use sed to delete all occurrences of <a name="foo">

I have multiple html documents and each one has many occurrences of
<a name="pIDsomestring">
where 'somestring' varies with each occurrence.
I want to delete the entire tag, as well as the
</a>
closing HTML tag that immediately follows it, but importantly, not the text inside the anchor tag.
Is there an easy way to do this with sed?
HTML is much more complicated than what can be parsed with sed. Two pieces of HTML can be absolutely equivalent, and yet look completely different as far as a sed command is concerned. For example, you can't really write a sed command that will recognize that these two are equivalent:
<a name="foo">bar</a>
<A
NAME = "foo"
><!-- </A> --bar</>-- -->
(The </>, if you're wondering, means </a> in this case. And heh, even Stack Overflow's syntax highlighter gets confused by the <!-- comment -- not-a-comment -- comment --> notation.)
The above is a pathological example, of course, but even perfectly-ordinary real-world HTML often has line-breaks and other whitespace in random places that have no effect on the HTML but a great deal of effect on a sed command.
But if you're just doing a one-off task where you can manually verify the results afterward, you can try something like this:
's#<a name="[^"]*">\(\([^<]\|<[^/]\|</[^a]\|</a[^>]\)*\)</a>#\1#g'
which will usually work as long as the whole thing is on one line.

Regular expression to remove repeated slashes that are after a specific word (VBScript/Classic ASP)

I'm struggling here, trying to figure out how to replace all double slashes that come after a specific word.
Example:
<img alt="" src="/pt/webf//2015//47384_1.JPG" height="235" width="378" />
<div>Don't remove this // or this//</div>
I want the string above to look like this:
<img alt="" src="/pt/webf/2015/47384_1.JPG" height="235" width="378" />
<div>Don't remove this // or this//</div>
Notice the double slashes have been replaced with just one slash in the img tag but left unscathed in the div tag. I only want to replace the double slashes IF they come after the word: pt.
I tried something like this:
(?=pt)((.*?)\/\/)+
However, the first thing wrong with it is (?=) does not do pattern backtracking, as far as I'm aware. That is, it'll only look for the first matching pattern. The second thing wrong with it is it doesn't work as I intended it to.
https://regex101.com/r/kC4tA5/1
Or maybe I'm going about this the wrong way, since regular expression support is not expansive in VBScript/Classic ASP and I should try to break up the string and process, instead of trying to do everything in one regular expression???
Any help would be appreciated.
Thank you.
I am interpreting your issue as "Removing repeated slashes in all <img src> attributes."
As I said in the comments, working with HTML requires a parser. HTML is too complex for regular expressions, all kinds of things can go wrong.
Luckily, there is a parser available to VBScript: The htmlfile object. It creates a standard DOM from your HTML string. So the solution becomes exactly as described:
Function FixHtml(htmlString)
Dim doc, img, slashes
Set slashes = New RegExp
slashes.Pattern = "/+"
slashes.Global = True
Set doc = CreateObject("htmlfile")
doc.Write htmlString
For Each img In doc.getElementsByTagName("IMG")
img.src = slashes.Replace(img.src, "/")
img.src = Replace(Replace(img.src, "about:blank", ""), "about:", "")
Next
FixHtml = doc.body.innerHTML
End Function
Unfortunately, htmlfile is not the most advanced HTML parser in the world, but rest assured that it will still do way better than any regex.
There are two minor issues:
I found in my tests that for some reason it insists on prepending the img.src with about: or about:blank. This should not happen, but it does. The second line of Replace() calls gets rid of the unwanted additions.
The .innerHTML will produce tags names in upper case, so <img> becomes <IMG> in the output. Also insignificant line breaks in the HTML source might be removed. This is a minor annoyance, I recommend you don't obsess over it.(*)
But there are two big plus sides as well:
The DOM puts you in a position where you can work with the input in a structured way. You can put in any number of complex fixes now that would have been impossible to do with regex.
The return value of .innerHTML is sane HTML. It will fix any gross blunder in the input and turn it into something that is well-nested, well-escaped and otherwise well-behaved.
(*) If you do find yourself obsessing over it, you can use the wisdom from this blog post to create a function that replaces all uppercase tags that come out of .innerHTML with lowercase versions of themselves. This actually is something you can use regex for ("(</?[A-Z]+)", to be exact), because we know that there will be no stray < not belonging to a tag anywhere in the string, because that's .innerHTML's guarantee. While it would be a nice exercise (and it introduces you to the little-known fact that VBScript has function pointers), I would say it's not really worth it.

RegEx help: need to grab images (Classic ASP)

I'm using the following expression in classic asp that successfully grabs any image tag with a .jpg and .png suffix.
re.Pattern = " ]*src=[""'][^ >]*(jpg|png)[""']"
The problem that I've found is many sites that I need to use do not actually use a suffix. So, I need to new regex that finds an image tag and grabs whatever is in the src attribute.
As simple as this sounds, finding an regular expression to accomplish this in Classic ASP seems impossible without writing it myself (which IS impossible).
Please advise.
To match plainly on the img src you can do:
\<img src\=\"(\w+\.(gif|jpg|png)\")
And then if you only want the value that's in the img src, you can do a match for anything in quotes ending in a picture extension (but this may get you false positives depending on what you want):
\w+\.(gif|jpg|png)
But to match just the value while ensuring that it follows img src, you need a negative lookahead to do this (note that I added a matching group there):
(?!.*\<img src\=\")(\w+\.(gif|jpg|png))
Now to include the possibility of having image links in your image source:
(?!.*\<img src\=\")([\/\.\-\:\w]+\.(gif|jpg|png)?[\?\w+\%]+)
And then let's remove the false positives we get by fixing that lazy quantifier after (gif|jpg|png) and moving it to after the next set (which matches data you may get in a JS link, etc.) and making sure we have an end quote:
(?!.*\<img src\=\")([\/\.\-\:\w]+\.(gif|jpg|png)([\?\w+\%]+)?)(?=\")
Note: This will match this data, but regular expressions don't parse HTML, and I personally don't recommend using regular expressions to look through HTML data unless you're doing it on a case-by-case basis. If you're wanting to do some URL/Image scraping via a script, look into an XML/HTML parser.
Sample data:
<img src="picture.gif">
<img src="pic859.jpg">
<img src="859.png">
<img id="test1" class="answer1" src="text.jpg">
<img src="http://media.site.com/media/img/staff/2013/ROTHBARD-350_s90x126.jpg?e3e29f4a7131cd3bc7c4bf334be801215db5e3c2%22%3E">
<img src="yahoo.com/images/imagename.gif">
HTML Source

Need to replace dynamic image tag with text

I need to replace the below url (including img tags) with text. I am not very good with regex... As you can see its dynamic with dates, and it ends in two different ways:
with alt=";)"> and sometimes with class="wp-smiley" />
<img src="http://thailandsbloggare.se/wp-content/uploads/2012/10/icon_wink.gif" alt=";)">
and sometimes with class="wp-smiley" at the end
<img src="http://thailandsbloggare.se/wp-content/uploads/2012/09/icon_wink.gif" alt=";)" class="wp-smiley" />
So any time this image is posted I want the complete string to replaced to text ";)"
I have managed to write the regex for everything until alt=";)"> and sometimes with class="wp-smiley" /> but then I am stuck, pressume need some OR functionality here.
<img src="http://thailandsbloggare.se/wp-content/uploads/20\d\d/\d+/icon_wink\.gif
Updated information after replies below
<img src="http://thailandsbloggare.se/wp-content/uploads/20[0-9]{2}/[01][0-9]/icon_wink.gif" alt=";\)" *(|class="wp-smiley")?>
and
Both fail returning strings whith class="wp-smiley" /> included
Its a site built in Wordpress using PHP and I am using http://urbangiraffe.com/plugins/search-regex/
Thanks in advance!
Normally, in a regex, you can create alternative sub-regexes:
(match this|or this)
In your case
(alt=";\)"|class="wp-smiley")
If alt=";)" is always there, do:
alt=";\)" *(|class="wp-smiley")
Of course, we don't know in which editor or programming language you are operating, and the actual regex implementation can be different from the above example.
Try the following pattern search:
<img src="http://thailandsbloggare.se/wp-content/uploads/20[0-9]{2}/[01][0-9]/icon_wink.gif" alt=";\)"(\sclass="wp-smiley")?>
Please refer to the syntax supported by the regex engine you are using. But, for most engines the above pattern should work. Note the character class used for date ranges, you should change it appropriately.

replacing image path with regular expression

I have massive html code, with loooads of images, problem is, every single image has a different path, example:
<img src="../media/2010/01/something.jpg" />
<img src="../media/logo.png" />
What I wanted to do with regular expressions is, to find every image path and replace it with:
<img src="../img/FILENAME.EXTENSION" />
I know that it's definately possible with regular expressions ... but it's just not my cup of tea, could any1 help me please?
Cheers, Mart
This might not be the best solution but it might work:
(<img.*?src=")([^"]*?(\/[^/]*\.[^"]+))
and then you use capture group 1 and 3 to create the new string (depending on flavor):
$1../img$3
You can see it in action here: http://regexr.com?2v8ir
If you want to parse html, its much better if you use an html parser instead of regex. There are quite alot of them and they do a very good work.
Html Agility Pack is a good one
Try this link
Using this regex <img src="[\w/\.]+"(\s|)/> and replacing with <img src="../img/FILENAME.EXTENSION" />