无法用 Perl 替换同一字符串中的模式
Unable to replace a pattern in the same string with Perl
我想将 <a>
标签更改为 HTML 文本(不是完整的 HTML 文档)中的外部链接。然而,如果该模式在同一行字符串中多次出现,则此 Perl 程序无法替换该模式。
这是一个示例程序:
use strict;
use warnings;
my $baseURL = "https://example.com";
my $input = <<'END';
<ul>
<li><a href="https://www.amazon.com">Amazon</a></li>
<li>
<!-- Keep it in one line. -->
<a href="https://www.google.com.tw">Google</a> and <a href="https://tw.yahoo.com">Yahoo</a> and <a href="https://duckduckgo.com">DuckDuckGo</a>
</li>
</ul>
END
# Replace external links globally.
$input =~ s{<a href=\"([^"]+)\">(.+)</a>}{
# Skip local URIs.
substr(, 0, 4) ne "http" ? "<a href=\"\"></a>"
# Skip links in same domain.
: index(, "$baseURL") >= 0 ? "<a href=\"\"></a>"
# Disable search engines from following links.
: "<a href=\"\" target=\"_blank\" rel=\"noopener nofollow\"></a>"}ge;
# Print modified input to STDOUT.
print $input;
(.+)
贪心,什么都抓到最后</a>
。请尝试使用 (.+?)
。
我想将 <a>
标签更改为 HTML 文本(不是完整的 HTML 文档)中的外部链接。然而,如果该模式在同一行字符串中多次出现,则此 Perl 程序无法替换该模式。
这是一个示例程序:
use strict;
use warnings;
my $baseURL = "https://example.com";
my $input = <<'END';
<ul>
<li><a href="https://www.amazon.com">Amazon</a></li>
<li>
<!-- Keep it in one line. -->
<a href="https://www.google.com.tw">Google</a> and <a href="https://tw.yahoo.com">Yahoo</a> and <a href="https://duckduckgo.com">DuckDuckGo</a>
</li>
</ul>
END
# Replace external links globally.
$input =~ s{<a href=\"([^"]+)\">(.+)</a>}{
# Skip local URIs.
substr(, 0, 4) ne "http" ? "<a href=\"\"></a>"
# Skip links in same domain.
: index(, "$baseURL") >= 0 ? "<a href=\"\"></a>"
# Disable search engines from following links.
: "<a href=\"\" target=\"_blank\" rel=\"noopener nofollow\"></a>"}ge;
# Print modified input to STDOUT.
print $input;
(.+)
贪心,什么都抓到最后</a>
。请尝试使用 (.+?)
。