2015-04-02 99 views
0

我需要用新的GUID替換所有的「0000-000」字符串。所以字符串中的每個「0000-000」應該有一個新的GUID。到目前爲止,我已經能夠用1個新的GUID替換全部。這裏是一個非常基本的代碼:如何用新的GUID替換子字符串000-000

private string ReplaceGuids(string xmlContent) 
{ 
    string fakeGuid = "00000000-0000-0000-0000-000000000000"; 
    xmlContent = @"<!--<workflow id=""00000000-0000-0000-0000-000000000000"">--><!--<workflow id=""00000000-0000-0000-0000-000000000000"">-->"; 

    //Method 1: replaces all 000000-00000 with the same new GUID 
    xmlContent = xmlContent.Replace(fakeGuid, Guid.NewGuid().ToString().ToUpper()); 

    //Method 2: also replacs all 0000-00000 with the same GUID 
    int pos = -1; 
    do 
    { 
     pos = xmlContent.IndexOf(fakeGuid); 
     if (pos > 0) 
     { 
      xmlContent = xmlContent.Replace(fakeGuid, Guid.NewGuid().ToString().ToUpper()); 
     } 

    } while (pos > 0); 

    return xmlContent; 
} 

我以前用過的正則表達式,但不知道如何讓每個000-000獲得不同的新的GUID。謝謝!

回答

4

您可以使用Regex.Replace方法以及帶有匹配評估程序的重載,以便您可以爲每個匹配項創建一個新的替換字符串。

由於您正在替換特定的字符串,請使用Regex.Escape方法來轉義其中將具有特殊含義的任何字符作爲模式。

xmlContent = Regex.Replace(
    xmlContent, 
    Regex.Escape(fakeGuid), 
    m => Guid.NewGuid().ToString().ToUpper() 
); 

你的第二個方法也將工作,如果你沒有使用Replace把GUID的字符串,而是使用Substring得到部分之前和之後的部分來代替:

int pos = -1; 
do { 
    pos = xmlContent.IndexOf(fakeGuid); 
    if (pos > 0) { 
    xmlContent = 
     xmlContent.Substring(0, pos) + 
     Guid.NewGuid().ToString().ToUpper() + 
     xmlContent.Substring(pos + fakeGuid.Length); 
    } 
} while (pos > 0); 
+0

真棒謝謝! – Max 2015-04-02 15:54:17