微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 用于转换超链接的RegExp帮助

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

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/abcdef,http://www.smh.com.au和www.hotmail.com,但不是http://www.aaaaaaaa.com,因为它被包装围绕< a>标签已经.

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

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

我不知道如何排除已包含在< a>中的内容或者< img>

救命 :)

编辑

对于那些稍后阅读的人来说,这是我提出的最终解决方

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

解决方法

你可以用

@"(?<!<\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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐