Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Regexp: Match anything except a certain word

by wfsp (Abbot)
on Apr 21, 2006 at 18:14 UTC ( [id://544957]=note: print w/replies, xml ) Need Help??


in reply to Regexp: Match anything except a certain word

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 :-))

Replies are listed 'Best First'.
Re^2: Regexp: Match anything except a certain word
by ikegami (Patriarch) on Apr 21, 2006 at 19:21 UTC
    Close. You missed the "unless they already have a target" condition specified by the OP. For example,
    <a href="http://example.com" target="foo">here</a>
    shouldn't change, but it becomes
    <a href="http://example.com" target="_target">here</a>

    Update: Added example.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://544957]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (1)
As of 2024-04-25 02:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found