2012-01-19 18 views
0

我想檢測文本格式的電子郵件,以便我可以將錨標籤放在它們上面,使用mailto標籤定位。我有它的正則表達式,但代碼還可以檢測已經由錨標記封裝或位於錨標記mailto參數中的電子郵件。使用正則表達式在文本中檢測電子郵件

我的正則表達式是:

([\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?) 

但它檢測到在下面的示例文本3場比賽:

ttt <a href='mailto:[email protected]'>[email protected]</a> abc [email protected] 

我只想[email protected]由正則表達式匹配。

+0

只需在正則表達式執行之前刪除錨標籤... –

+0

你必須使用正則表達式嗎? –

+0

http://stackoverflow.com/questions/1903356/email-validation-regular-expression – Clive

回答

2

非常相似,我previous answer到您的其他問題,試試這個

(?<!(?:href=['"]mailto:|<a[^>]*>))(\b[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?) 

的這是唯一真正不同的是電子郵件開始前的字邊界\b

看到類似的表達here on Regexr,它不完全相同,因爲Regexr不支持lookbehind中的交替和無限長度。

+0

還有一個問題,當錨標記中有雙引號{「}時,你的正則表達式不起作用:href =」somelink「它對於錨標記中的href中的單引號。例如:href ='somelink'你可以幫助編輯lookbehind,因此它包含單引號{'}和雙引號{「} –

+0

@Ankit我更新了我的答案。 – stema

-1

只需插入一個\ s +就在您的左括號後,像這樣:

(\s+[\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?) 

這樣你只會得到後空間的電子郵件,忽略那些經過mailto:或關閉標籤(>) 。

+0

關於文本正文的郵件怎麼樣?那些不會被捕獲。 –

+0

斯特瑪的答案似乎是最好的答案。我的方式太懶了...... :) –

1

這是一個更好的主意到HTML的解析留給適用於(作爲HtmlAgilityPack這樣的)東西,並結合起來,與正則表達式來更新文本節點:

string sContent = "ttt <a href='mailto:[email protected]'>[email protected]</a> abc [email protected]"; 
    string sRegex = @"([\w-]+(\.[\w-]+)*@([a-z0-9-]+(\.[a-z0-9-]+)*?\.[a-z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?)"; 
    Regex Regx = new Regex(sRegex, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); 

    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
    doc.LoadHtml(sContent); 

    var nodes = doc.DocumentNode.SelectNodes("//text()[not(ancestor::a)]"); 
    foreach (var node in nodes) 
    { 
     node.InnerHtml = Regx.Replace(node.InnerHtml, @"<a href=""mailto:$0"">$0</a>"); 
    } 
    string fixedContent = doc.DocumentNode.OuterHtml; 

我注意到你已經發布同樣的問題other forums as well,但沒有在他們中任何一個指定答案。

相關問題