2011-07-04 14 views
1

我想我需要使用一個替代構造,但我不能讓它工作。我怎樣才能把這個邏輯變成一個正則表達式模式?如何使用一個正則表達式模式而不是三個來執行此操作?

match = Regex.Match(message2.Body, @"\r\nFrom: .+\(.+\)\r\n"); 
if (match.Success) 
    match = Regex.Match(message2.Body, @"\r\nFrom: (.+)\((.+)\)\r\n"); 
else 
    match = Regex.Match(message2.Body, @"\r\nFrom:()(.+)\r\n"); 

編輯:

一些樣品的情況下應與您的問題

From: email 

From: name(email) 

那些幫助有兩種可能的情形。我正在尋找匹配他們,所以我可以做

string name = match.Groups[1].Value; 
string email = match.Groups[2].Value; 

對不同的方法的建議,歡迎! 謝謝!

+0

你想用你的表達來實現什麼?特別是第三個「()」有什麼用處? – stema

+0

你打算如何使用比賽?可能使用第一和第二組。 –

回答

3

這是從字面上你問的:"(?=" + regex1 + ")" + regex2 + "|" + regex3

match = Regex.Match(message.Body, @"(?=\r\nFrom: (.+\(.+\))\r\n)\r\nFrom: (.+)\((.+)\)\r\n|\r\nFrom:()(.+)\r\n"); 

但我不認爲這真的是你想要的。

使用.net的正則表達式,您可以命名爲這樣的組:(?<name>regex)

match = Regex.Match(message.Body, @"\r\nFrom: (?<one>.+)\((?<two>.+)\)\r\n|\r\nFrom: (?<one>)(?<two>.+)\r\n"); 

Console.WriteLine (match.Groups["one"].Value); 
Console.WriteLine (match.Groups["two"].Value); 

但是,您的\r\n可能是不正確的。這將是一個文字rnFrom:。試試這個。

match = Regex.Match(message.Body, @"^From: (?:(?<one>.+)\((?<two>.+)\)|(?<one>)(?<two>.+))$"); 

Console.WriteLine (match.Groups["one"].Value); 
Console.WriteLine (match.Groups["two"].Value); 
相關問題