2015-04-17 134 views
0

我需要找出所有字符串匹配大字符串緩衝區中的特定模式。如何找到具有特定模式的匹配字符串

例如,我有一個像

"2014:11:12 13:30:05 Tested for ABCD at 12:30 2014:11:12 13:31:05 Tested for ABBB at 12:31 2014:11:12 13:32:05 Tested for ABCC at 12:32" 

一個字符串,我想有一個像這樣的輸出:

2014:11:12 13:30:05 ABCD 12:30 
2014:11:12 13:31:05 ABBB 12:31 
2014:11:12 13:32:05 ABCC 12:32 

我曾嘗試用類似這樣的代碼:

string data = "2014:11:12 13:30:05 Tested for ABCD at 12:30 2014:11:12 13:31:05 Tested for ABBB at 12:31 2014:11:12 13:32:05 Tested for ABCC at 12:32"; 
MatchCollection matches = Regex.Matches("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} Tested for [?]{4} at [0-9]{2}:[0-9]{2}"); 

/* But matches.count is always 0 here, looks like the pattern [?]{4} not work */ 

foreach (Match match in matches) 
{ 
    string temp = match.Value; 
    Match dateTime = Regex.Match(temp, "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}"); 

    Match Org = Regex.Match(temp, "Tested for [?]{4}").Value, "[?]{4}"); 

    Match processingTime = Regex.Match(temp, "at [0-9]{2}:[0-9]{2}").Value, "[0-9]{2}:[0-9]{2}"); 

    /* then parse the field datetime, Org and processingTime and write to console */ 
} 
+4

你能告訴我們你試過的東西,告訴我們什麼沒有奏效嗎?也許那麼我們可以幫助你弄清楚什麼不起作用。 –

回答

0

你可以使用正則表達式。我不是這方面的專家,我相信這個工作存在更好的正則表達式表達式,但這應該做到這一點(省略錯誤捕獲)。

string input = "2014:11:12 13:30:05 Tested for ABCD at 12:30 2014:11:12 13:31:05 Tested for ABBB at 12:31 2014:11:12 13:32:05 Tested for ABCC at 12:32"; 
string regex = @"(\d{4}:\d{2}:\d{2} \d{2}:\d{2}:\d{2}) Tested for (.*?) at (\d{2}:\d{2})"; 
Regex r = new Regex(regex); 

var matchCollection = r.Matches(input); 
var outputStrings = matchCollection.Cast<Match>().Select(m => string.Format("{0} {1} {2}", m.Groups[1], m.Groups[2], m.Groups[3])).ToList(); 
outputStrings.ForEach(str => Console.WriteLine()); 
相關問題