How can I selectively modify the src attributes of

2019-07-21 18:28发布

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!

4条回答
Viruses.
2楼-- · 2019-07-21 18:50

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

s{
  (<script\s+src\s*=\s*[\'"])
  (?!https?://)
}{$1\[perl]texthere[/perl]}gsx;
查看更多
够拽才男人
3楼-- · 2019-07-21 18:53

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

查看更多
淡お忘
4楼-- · 2019-07-21 18:55

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.

查看更多
贼婆χ
5楼-- · 2019-07-21 19:06

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>
查看更多
登录 后发表回答