You need to tweak your regular expression a little bit. Let me start with this fast diddle:
$html =~ s/<IMG[^>]+?(?:ALT="([^"]*)"[^>]*)>/[image: "$1"]/sgi;
Let me explain what I did: I changed your .*? to [^>]+? for you only want to match non-end delimeters for the <img> tag in here, and also there I think it's more sensible to use + than * for there is no special need to catch all an empty tag, and there must at least be a whitespace inbetween :-)

Secondly, why did you escape the brackets in the alt-tag, and at the end? That doesn't really make sense, for you want the special meaning of it at that point. There is also no need to escape it in the replacement string for they don't have a special meaning there.

And, you need to put brackets with a ? followed around the alt-part for as you already noticed it wouldn't match tags without an alt-tag. I did it with (?: so it won't get stored.

This will produce the following:

<img foo><img alt="bar"> [image: ""][image: "bar"]
If you want to have just plain [image] in the replacement if there is no alt atribute present I guess that wouldn't be possible with a single substitute, but you can still do the following substitution afterwards:
$html =~ s/\[image: ""\]/[image]/g;
HTH & HAND!
--
Alfie

In reply to Re: Regex For HTML Image Tags? by alfie
in thread Regex For HTML Image Tags? by hostile17

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.