I agree with santonegro that a parser makes this a lot simpler. Let someone else do the heavy lifting. :-)
#!/bin/perl5 use strict; use warnings; use HTML::TokeParser::Simple; my $html; { local $/; $html = <DATA>; } my $tp = HTML::TokeParser::Simple->new(\$html) or die "Couldn't parse string: $!"; while (my $t = $tp->get_token) { if ( $t->is_start_tag('a') and $t->get_attr('href') =~ /^http/ and not $t->get_attr('target') ) { $t->set_attr('target', '_blank'); } print $t->as_is; } __DATA__ <a href="http://here.com" target="_blank">here</a> <a href="http://there.com">there</a> <a href="http://everywhere.com" target="foo">everywhere</a> <a href="local.html">local</a>
output:
---------- Capture Output ---------- > "C:\Perl\bin\perl.exe" parse_.pl <a href="http://here.com" target="_blank">here</a> <a href="http://there.com" target="_blank">there</a> <a href="http://everywhere.com" target="foo">everywhere</a> <a href="local.html">local</a> > Terminated with exit code 0.
Update: Covered the "unless they already have a target" condition as pointed out by ikegami below. I would argue that fixing/changing this script is easier than fixing a regex (but I would say that wouldn't I :-))

In reply to Re: Regexp: Match anything except a certain word by wfsp
in thread Regexp: Match anything except a certain word by fraktalisman

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.