正则表达式用链接替换单词 [英] Regular expression replace a word by a link

查看:36
本文介绍了正则表达式用链接替换单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个正则表达式,用链接替换巴黎这个词,因为只有这个词还没有准备好成为链接的一部分.

I want to write a regular expression that will replace the word Paris by a link, for only the word is not ready a part of a link.

示例:

    i'm living <a href="Paris" atl="Paris link">in Paris</a>, near Paris <a href="gare">Gare du Nord</a>,  i love Paris.

会变成

    i'm living.........near <a href="">Paris</a>..........i love <a href="">Paris</a>.

推荐答案

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

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>";
    }
}

这篇关于正则表达式用链接替换单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆