2012-02-13 214 views
1

我有字符串,我需要分割它兩次,選擇特殊字符後面的部分。C#正則表達式分割和正則表達式

比方說:

string myString = "Word 2010|82e146e7-bc85-4bd4-a691-23d55c686f4b;#Videos|55140947-00d0-4d75-9b5c-00d8d5ab8436"; 

string[] guids = Regex.Split(myString,";#"); 

所以在這裏我得到與價值+ GUID兩個元素的數組。但我只需要的GUID,如:

[0] 82e146e7-bc85-4bd4-a691-23d55c686f4b

[1] 55140947-00d0-4d75-9b5c-00d8d5ab8436

任何方式做一兩行?

+1

有一件事值得一提的是,使用' Regex.Split'(在上面的上下文中)而不是'String.Split'是毫無意義的(我懷疑會有更多的開銷)。我個人只有兩個功能,一個按照上面的方式拆分,另一個在管道上拆分。 – Chris 2012-02-13 17:27:47

回答

5

你可以做到這一點,但僅僅是因爲你可以做到在同一行,並不意味着你應該(可讀性進場,如果你太看中這裏)。這裏顯然沒有驗證。

string myString = "Word 2010|82e146e7-bc85-4bd4-a691-23d55c686f4b;#Videos|55140947-00d0-4d75-9b5c-00d8d5ab8436"; 

string[] guids = Regex.Split(myString, ";#") 
         .SelectMany(s => Regex.Split(s, @"\|").Skip(1)) 
         .ToArray(); 

Assert.AreEqual(2, guids.Length); 
Assert.AreEqual("82e146e7-bc85-4bd4-a691-23d55c686f4b", guids[0]); 
Assert.AreEqual("55140947-00d0-4d75-9b5c-00d8d5ab8436", guids[1]); 
3

你可以很容易地做到這一點沒有一個正則表達式,如果每個的最後部分始終是一個GUID:

string[] guids = String.Split(";").Select(c => c.Substring(c.Length - 36)).ToArray(); 
0
string[] guids = myString.Split(';').Select(x => x.Split('|')[1]).ToArray(); 
0
string myString = "Word 2010|82e146e7-bc85-4bd4-a691-23d55c686f4b;#Videos|55140947-00d0-4d75-9b5c-00d8d5ab8436"; 

//split the string by ";#" 
string[] results = myString.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries); 

//remove the "value|" part 
results[0] = results[0].Substring(results[0].IndexOf('|') + 1); 
results[1] = results[1].Substring(results[1].IndexOf('|') + 1); 

//Same as above, but in a for loop. usefull if there are more then 2 guids to find 
//for(int i = 0; i < results.Length; i++) 
// results[i] = results[i].Substring(results[i].IndexOf('|') + 1); 

foreach(string result in results) 
    Console.WriteLine(result); 
0
var guids = Regex 
    .Matches(myString, @"HEX{8}-HEX{4}-HEX{4}-HEX{4}-HEX{12}".Replace("HEX", "[A-Fa-f0-9]")) 
    .Cast<Match>() 
    .Select(m => m.Value) 
    .ToArray();