2013-02-27 57 views
-2
const string input = "===== Action: [Action1] State: [State1] by:[user1] at [timestamp1] ===== [Notes1]===== Action: [Action2] State: [State2] by:[user2] at [timestamp2] ===== [Notes2]"; 

Regex expression = new Regex(@"===== Action: (?<Action>.*?)State:(?<State>.*?)by:(?<userid>.*?)at(?<timestamp>.*?)=====(?<Note>.*?)"); 

var results = expression.Matches(input); 
foreach (Match match in results) 
{ 
    Console.WriteLine("UserId:" + match.Groups["userid"].Value); 
    Console.WriteLine("Action:" + match.Groups["Action"].Value); 
    Console.WriteLine("State:" + match.Groups["State"].Value); 
    Console.WriteLine("TimeStamp:" + match.Groups["timestamp"].Value); 
    Console.WriteLine("Note:" + match.Groups["Note"].Value); 
} 

我能夠正確解析除Note之外的所有值。任何想法我做錯了什麼?如何匹配行尾的句子?

+1

我編輯了自己的冠軍。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 – 2013-02-27 16:50:47

+0

我們能否定義您的需求和/或預期產出與實際產出? – 2013-02-27 16:52:23

回答

1

你忘了使用(?======|$)regex .. (?<Note>.*?)在你的正則表達式的結尾會匹配一切,直到最終這是不是你想要的..

所以正則表達式將

===== Action: (?<Action>.*?)State:(?<State>.*?)by:(?<userid>.*?)at(?<timestamp>.*?)=====(?<Note>.*?)(?======|$) 

如果輸入被換行符分隔,使用SinglelineMode選項

+0

謝謝,這工作! – user1889978 2013-02-27 18:37:20

1

我的心理調試感覺告訴我,在你的正則表達式的末尾.*?不貪心,a nd只會選擇0個空格(滿足.*?)。

我想你可能要在某些符號上班到兩個你的輸入和你的正則表達式來確定,其中Note的到底應該

+0

我不認爲它會返回任何字符(因爲'。*?'應該匹配「儘可能少的任意數量的字符,包括0」) – Nuffin 2013-02-27 17:01:24

+0

@Nuffin固定.. – 2013-02-27 17:02:14