簡體   English   中英

無法用 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($1, 0, 4) ne "http" ? "<a href=\"$1\">$2</a>"
    # Skip links in same domain.
    : index($1, "$baseURL") >= 0 ? "<a href=\"$1\">$2</a>"
    # Disable search engines from following links.
    : "<a href=\"$1\" target=\"_blank\" rel=\"noopener nofollow\">$2</a>"}ge;

# Print modified input to STDOUT.
print $input;

(.+)是貪婪的,並捕獲所有內容到最后</a> 嘗試使用(.+?)代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM