2012-05-15 42 views
3

我有不同的選擇,我的GUIDS如何作爲字符串行存儲。從字符串行解析GUID

1. Accessibility|5102d73a-1b0b-4461-93cd-0c024738c19e 
2. 5102d73a-1b0b-4461-93cd-0c024738c19e;#5102d73a-1b0b-4461-93cd-0c024733d52d 
3. |;#5102d73a-1b0b-4461-93cd-0c024738c19e;#SharePointTag|5102d73a-1b0b-4461-93cd-0c024733d52d 
3. Business pages|;#5102d73a-1b0b-4461-93cd-0c024738cz13;#SharePointTag|5102d73a-1b0b-4461-93cd-0c024733d52d 

難道你們幫我出主意,我怎麼能分析這個標籤,並最終獲得的GUID類型的列表?也許正則表達式可以幫助在這種情況下?

+3

您是否使用您提供的所有示例?或者您是否希望選擇其中一個示例作爲存儲指導的方式?你能否提供你想要做的更多的信息。 – Purplegoldfish

+0

看着你的數據結構,我在想你需要首先對你的數據結構進行排序,然後決定你想使用的分隔符。我可以看到'| ,; #' –

回答

4

你看上去與託管元數據,術語庫ID和術語集ID :)

只需使用常規的打正則表達式(下稱 「p」 下方變量):

string c1 = "Accessibility|5102d73a-1b0b-4461-93cd-0c024738c19e"; 
string c2 = "5102d73a-1b0b-4461-93cd-0c024738c19e;#5102d73a-1b0b-4461-93cd-0c024733d52d"; 
string c3 = "|;#5102d73a-1b0b-4461-93cd-0c024738c19e;#SharePointTag|5102d73a-1b0b-4461-93cd-0c024733d52d"; 
string c4 = "Business pages|;#5102d73a-1b0b-4461-93cd-0c024738cz13;#SharePointTag|5102d73a-1b0b-4461-93cd-0c024733d52d"; 
string p = @"([a-z0-9]{8}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{12})"; 

MatchCollection mc; 

Console.WriteLine("#1"); 
mc = Regex.Matches(c1, p); 
foreach (var id in mc) 
    Console.WriteLine(id); 

Console.WriteLine("#2"); 
mc = Regex.Matches(c2, p); 
foreach (var id in mc) 
    Console.WriteLine(id); 

Console.WriteLine("#3"); 
mc = Regex.Matches(c3, p); 
foreach (var id in mc) 
    Console.WriteLine(id); 

Console.WriteLine("#4"); 
mc = Regex.Matches(c4, p); 
foreach (var id in mc) 
    Console.WriteLine(id); 

WICH輸出:

#1 
5102d73a-1b0b-4461-93cd-0c024738c19e 
#2 
5102d73a-1b0b-4461-93cd-0c024738c19e 
5102d73a-1b0b-4461-93cd-0c024733d52d 
#3 
5102d73a-1b0b-4461-93cd-0c024738c19e 
5102d73a-1b0b-4461-93cd-0c024733d52d 
#4 
5102d73a-1b0b-4461-93cd-0c024738cz13 
5102d73a-1b0b-4461-93cd-0c024733d52d 
Press any key to continue... 
1

例如,您可以將字符串分割

"fist|second".Split('|') 

你,一旦你得到GUID的字符串轉換它使用

Guid = new Guid(myString); 

對於第一線

var guid = new Guid("Accessibility|5102d73a-1b0b-4461-93cd-0c024738c19e".Split("|")[1]); 

對於第二行GUID

var myArray = "5102d73a-1b0b-4461-93cd-0c024738c19e;#5102d73a-1b0b-4461-93cd-0c024733d52d".Split(';'); 
var guid1 = new Guid(myArray[0]); 
var guid2 = new Guid(myArray[1].Replace('#','')); 

所以,你可以繼續這樣..

2
string sContent = "your data"; // any of your four forms of input 
string sPattern = @"([a-z0-9]*[-]){4}[a-z0-9]*"; 

MatchCollection mc = Regex.Matches(sContent, sPattern); 

foreach (var sGUID in mc) 
{ 
    // Do whatever with sGUID 
} 
+0

'5102d73a-1b0b-4461-93cd-0c024738cz13'將傳遞你的模式,但是'Guid.TryParse'返回false。 – Damith

+0

很好的解決方案!謝謝。但有一個bug,它只是我的一部分:5102d73a-1b0b-4461-93cd –

4
var possibleGuids = myString.Split("|;#".ToCharArray(), 
            StringSplitOptions.RemoveEmptyEntries); 
Guid g; 
foreach(var poss in possibleGuids) 
{ 
    if(Guid.TryParse(poss, out g)) 
    { 
     // g contains a guid! 
    } 
}