【发布时间】: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/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>";
}
【问题讨论】: