2011-02-16 64 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