2011-02-16 66 views
4

我想拿出一个正则表达式,并尝试了很多组合,并试图找到解决方案将非超链接地址转换为超链接。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/abcdefhttp://www.smh.com.auwww.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>"; 
} 

回答

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 
+0

我没有张贴此之前实际读取负向后断言,但没有意义的,我..还是犯规。 它适用于'',但它仍然为``找到它。我将如何修改它,以便如果地址以`www`开始,替换会添加到`http://'中? – 2011-02-16 11:12:43