且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式用链接替换单词

更新时间:2023-02-23 12:54:01

你可以搜索这个正则表达式:

You could search for this regular expression:

(<a[^>]*>.*?</a>)|Paris

这个正则表达式匹配一个链接,它捕获到第一个(也是唯一一个)捕获组,或单词 Paris.

This regex matches a link, which it captures into the first (and only) capturing group, or the word Paris.

仅当捕获组不匹配任何内容时,才用您的链接替换匹配项.

Replace the match with your link only if the capturing group did not match anything.

例如在 C# 中:

resultString = 
    Regex.Replace(
        subjectString, 
        "(<a[^>]*>.*?</a>)|Paris", 
        new MatchEvaluator(ComputeReplacement));

public String ComputeReplacement(Match m) {
    if (m.groups(1).Success) {
        return m.groups(1).Value;
    } else {
        return "<a href=\"link to paris\">Paris</a>";
    }
}