2015-08-14 73 views
2

您好我有我需要的格式(列)電子郵件CSV文件的電子郵件,他們在CSV如下如何提取從HTML鏈接

<a href=\mailto:[email protected]\">[email protected]</a>" 
<a href=\mailto:[email protected]\">[email protected]</a>" 

等等

所以我要刪除<a href=\mailto:[email protected]\"> </a>",只需使用[email protected]

我有以下

foreach (var clientI in clientImportList) 
          { 
newClient = new DomainObjects.Client(); 
//Remove unwanted email text?? 
           newClient.Email = clientI.Email 
          } 
+0

你必須使用第二個地址嗎?使用第一種方法會更容易,在您的示例中它們是相同的。 – EAnders

+0

你是否對子串和正則表達式做過任何研究? –

+0

獲取「>」符號的索引,然後得到之後出現的「<」符號的索引,執行SubString。 – LarsTech

回答

-1

我通常自己寫一些小工具類和擴展來處理這樣的事情。由於這可能不會是最後一次,你必須做這樣的事情,你可以這樣做:

創建String類的擴展:

public static class StringExtensions 
{ 
    public static string ExtractMiddle(this string text, string front, string back) 
    { 
     text = text.Substring(text.IndexOf(front) + 1); 
     return text.Remove(text.IndexOf(back)); 
    } 
} 

然後做到這一點(能使用更好的命名,但你明白了):

string emailAddress = text.ExtractMiddle(">", "<"); 
+0

謝謝你,工作愉快! –

+0

'IndexOf'採用'char'而不是'string'。所以如果你用這個來傳遞一個超過1個字符的字符串,結果是不可預知的。 – Shiva

3

我會建議使用HtmlAgilityPack,而不是你自己分析吧:

HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml(html); 

foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"]) 
{ 
    string href = link["href"].Value; 
    // use "mailto:[email protected]" here.. 
} 
-1

如果你想這樣做索引的方式,是這樣的:

 const string start = "<a href=\\mailto:"; 
     const string end = "\\\">"; 
     string asd1 = "<a href=\\mailto:[email protected]\\\">[email protected]</a>\""; 
     int index1 = asd1.IndexOf(start); 
     int startPosition = index1 + start.Length; 
     int endPosition = asd1.IndexOf(end); 
     string email = asd1.Substring(startPosition, endPosition - startPosition); 
0

你可以在這裏測試正則表達式: https://regex101.com/

使用你的例子,這似乎工作:

mailto:(.*?)\\"> 

正則表達式需要的庫是:

using System.Text.RegularExpressions;