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!
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!
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>
Use the negative lookahead pattern (on the third line below):
s{
(<script\s+src\s*=\s*[\'"])
(?!https?://)
}{$1\[perl]texthere[/perl]}gsx;
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.
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