How can I selectively modify the src attributes of

2019-07-21 19:01发布

问题:

I need to write a regular expression in Perl that will prefix all srcs with [perl]texthere[/perl], like such:

 <script src="[perl]texthere[/perl]/text"></script> 

Any help? Thanks!

回答1:

Use a proper parser such as HTML::TokeParser::Simple:

#!/usr/bin/env perl

use strict; use warnings;
use HTML::TokeParser::Simple;

my $parser = HTML::TokeParser::Simple->new(handle => \*DATA);

while (my $token = $parser->get_token('script')) {
    if ($token->is_tag('script')
            and defined(my $src = $token->get_attr('src'))) {
            $src =~ m{^https?://}
                or  $token->set_attr('src', "[perl]texthere[/perl]$src");
    }
    print $token->as_is;
}

__DATA__
<script src="/js/text.text.js/"></script>

And at the same time, ignore scrs that begin with http, as such:

 <script src="https://websitewebsitewebsite"></script>

Output:

<script src="[perl]texthere[/perl]/js/text.text.js/"></script>

And at the same time, ignore scrs that begin with http, as such:

 <script src="https://websitewebsitewebsite"></script>


回答2:

Use the negative lookahead pattern (on the third line below):

s{
  (<script\s+src\s*=\s*[\'"])
  (?!https?://)
}{$1\[perl]texthere[/perl]}gsx;


回答3:

I am able to match any src=" except for http via: ^<script src="(?!(https:)).*$ Let me know if there are any issues and I'll fix it.

Try using: this website as a regex tutorial and this website to test regex.



回答4:

This should work:

 s{(?<=src=)(?!"https?)}{[perl]texthere[/perl]}

Test:

 my @olnk = ('<script src=/js/text.text.js/"></script>',
             '<script src="https://websitewebsitewebsite"></script>' );
 my @nlnk = map {
                  s{(?<=src=)(?!"https?)}{[perl]texthere[/perl]}; $_
                } @olnk;

Result:

 print join "\n", @nlnk;

 <script src=[perl]texthere[/perl]/js/text.text.js/"></script>
 <script src="https://websitewebsitewebsite"></script>

Regards

rbo