【问题标题】:RegExp help for converting hyperlinks用于转换超链接的 RegExp 帮助
【发布时间】:2011-06-28 04:18:21
【问题描述】:

我正在尝试提出一个正则表达式,并尝试了许多组合并搜索以找到将非超链接地址转换为超链接的解决方案。

http://twitpic.com/abcdef http://www.smh.com.au askjhsd www.hotmail.com ks sd 
<a href="http://www.aaaaaaaa.com">aaaaaaaa</a>

我希望获取http://twitpic.com/abcdefhttp://www.smh.com.auwww.hotmail.com,而不是http://www.aaaaaaaa.com,因为它已经包裹在&lt;a&gt; 标签上。

我目前在 C# 中使用这个正则表达式

return Regex.Replace(input, @"(\b((http|https)://|www\.)[^ ]+\b)", 
   @" <a href=""$0"" target=""_blank"">$0</a>", RegexOptions.IgnoreCase);

我不知道如何让它排除已经包含在 &lt;a&gt;&lt;img&gt; 中的东西

帮助:)

编辑

对于那些稍后阅读本文的人,这是我想出的最终解决方案

/// <summary>
/// Adds to the input string a target=_blank in the hyperlinks
/// </summary>
public static string ConvertURLsToHyperlinks(string input)
{
    if (!string.IsNullOrEmpty(input))
    {
        var reg = new Regex(@"(?<!<\s*(?:a|img)\b[^<]*)(\b((http|https)://|www\.)[^ ]+\b)");
        return reg.Replace(input, new MatchEvaluator(ConvertUrlsMatchDelegate));

    }
    return input;
}

public static string ConvertUrlsMatchDelegate(Match m)
{
    // add in additional http:// in front of the www. for the hyperlinks
    var additional = "";
    if (m.Value.StartsWith("www."))
    {
        additional = "http://";
    }
    return "<a href=\"" + additional + m.Value + "\" target=\"_blank\">" + m.Value + "</a>";
}

【问题讨论】:

    标签: c# regex url


    【解决方案1】:

    你可以使用

    @"(?<!<\s*(?:a|img)\b[^<]*)(\b((http|https)://|www\.)[^ ]+\b)"
    

    作为您的正则表达式。 negative lookbehind assertion

    后向断言解释:

    (?<!       # Assert that it's impossible to match before the current position:...
     <         # a <
     \s*       # optional whitespace
     (?:a|img) # a or img
     \b        # as an entire word
     [^<]*     # followed by any number of characters except <
    )          # end of lookbehind
    

    【讨论】:

    • 在发布之前我确实读过那个负面的后向断言,但对我来说毫无意义..仍然没有。它适用于&lt;a&gt;,但它仍然适用于&lt;img&gt;。我将如何修改它以便如果地址以www 开头,则替换将添加http://
    • 我忽略了 img 标签位 - 已编辑我的答案并添加了解释。
    • 太棒了!!!这很有效,谢谢你的解释。最后,我将如何修改它,如果地址以www 开头,替换将添加一个额外的http://
    • 我会在两个不同的正则表达式中做到这一点。一个是左边的,一个是右边的 - 只在后一个的替换文本中添加http://
    猜你喜欢
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    相关资源
    最近更新 更多