2014-02-06 46 views
0

我想在c#中使用正則表達式從電子郵件中提取一些信息。使用正則表達式從郵件中提取信息

這裏是從電子郵件中的一小段:

...with mapi id 14.02.0387.000; Thu, 6 Feb 2014 09:09:33 +0100 
From: site <[email protected]> 
To: "[email protected]" <[email protected]> 
Subject: can this bounce 
Thread-Topic: can this bounce 
Thread-Index: Ac8jEr8t3k2RouQ1RaGPCXGFcE5oNg==Date:... 

我想提取「從」的<>之間的地址,「收件人」 <>和主題(在本例之間的地址,主題是「can this bounce」)

我對正則表達式並不是很熟悉,所以我會很感激任何幫助。

(順便說一句和,如果有一個更簡單更巧妙的解決辦法我會很高興地聽到!)使用LINQ

+0

http://hpop.sourceforge.net/ – nhahtdh

回答

1

:A液(。*?)

var fromAddress = new string(msg.SkipWhile(c => c != '<').Skip(1).TakeWhile(c => c != '>').ToArray()); 

var toAddress = new string(msg.Substring(msg.IndexOf("To")).SkipWhile(c => c != '<').Skip(1).TakeWhile(c => c != '>').ToArray()); 

var subject = new string(msg.Substring(msg.IndexOf("Subject")).SkipWhile(c => c != ' ').Skip(1).TakeWhile(c => c != 'T').ToArray()); 
+0

很整齊,和它的作品!現在唯一的問題是,實際郵件由許多行組成......並且滿足LINQ表達式中的要求的第一行其實不是正確的,所以我需要跳過第一行。是否有辦法使它選擇字符串中的最後一行,而不是第一行? –

+0

你可以用'string.Substring'跳過第一行,例如'message.Substring(message.IndexOf(「startFromHere」))' –

0

\ <>

  • \ <:<是元字符,需要進行轉義,如果你想匹配它 字面上。
  • (。*?):以非貪婪的方式匹配所有內容並捕獲它。
  • >:>是一個元字符,需要轉義,如果你想從字面上匹配 。
1

全運行例如使用正則表達式:
我用圖案與3組:
@"[Ff]rom:[^<]*\<([^@][email protected][^>]+)>[Tt]o:[^<]*\<([^@][email protected][^>]+)>[Ss]ubject: ?(.*)Thread-Topic"

string source = "...with mapi id 14.02.0387.000; Thu, 6 Feb 2014 09:09:33 +0100From: site <[email protected]>To: \"[email protected]\" <[email protected]>Subject: can this bounceThread-Topic: can this bounceThread-Index: Ac8jEr8t3k2RouQ1RaGPCXGFcE5oNg==Date:..."; 
Regex pattern = new Regex("[Ff]rom:[^<]*\\<([^@][email protected][^>]+)>[Tt]o:[^<]*\\<([^@][email protected][^>]+)>[Ss]ubject: ?(.*)Thread-Topic"); 
MatchCollection mc = pattern.Matches(source); 
string partFrom = ""; string partTo = ""; string subject = ""; 
if(mc.Count>0) 
{ 
    partFrom = mc[0].Groups[1].Value; 
    partTo = mc[0].Groups[2].Value; 
    subject = mc[0].Groups[3].Value; 
} 
Console.WriteLine("From: " + partFrom + " To: " + partTo + " Subject: " + subject); 

我檢查,如果內部郵件符號(存在@)在我的表達和提取物所有部分都是單一模式。
如果你想找到只有電子郵件地址,你可以使用這個表達式:

@"\<[^>@][email protected][^>]+>" 
+0

我剛試過你的解決方案,但由於某種原因,mc.Count永遠不會> 0 .. :( –

+0

我測試我的解決方案,我得到這個結果:'From:[email protected]到:[email protected]主題:這可以反彈嗎?所以你不可能得到不同的結果。我相信你使用了不同的輸入。你能發送你測試過的字符串「source」的全部內容嗎? ..或更新你的問題,並寫下你已經測試過的東西。 – Atiris

+0

嗨Atiris,是的,我使用不同的輸入字符串。沒有張貼在這裏,因爲它相當長。是否有可能在這裏使用一些郵件系統發送它,或者你想怎麼做? –

0

我用你的源文本試過這使用RegexBuddy與.NET的味道,它打破它變成一個名爲捕獲組,這樣就可以使用match.Groups [「FROM」]。值等

然後,您可以迭代匹配以確定匹配是否包含指定捕獲組中的值。在匹配可能不完整的文檔時,我使用過這種方法。

(?:From: .+<(?<FROM>.+)>)?(?:To: .+<(?<TO>.+)>)?(?:Subject: (?<SUBJECT>.+))?

+0

與Atiris的答案一起使用:) – Tom

相關問題