2012-07-12 107 views
1

我有一個字符串,其中「特殊區域」括在大括號來改寫的字符串:如何通過模式

{intIncG}/{intIncD}/02-{yy} 

我需要的基礎上,通過所有這些元素其間{的迭代}和替換它們關於他們的內容。什麼是最好的代碼結構在C#中做到這一點?

我不能只是做一個替換,因爲我需要知道每個「speacial area {}」的索引,以便用正確的值替換它。

+0

所以拆分或更換? – sll 2012-07-12 10:18:27

+0

只是索引?您不會根據{}內的內容更改替換項嗎? – BonyT 2012-07-12 10:22:18

+0

兩者都需要考慮 - 索引和內容 - 實際代碼。 – 2012-07-12 10:46:46

回答

2
Regex rgx = new Regex(@"\({[^\}]*\})"); 
string output = rgx.Replace(input, new MatchEvaluator(DoStuff)); 


static string DoStuff(Match match) 
{ 
//Here you have access to match.Index, and match.Value so can do something different for Match1, Match2, etc. 
//You can easily strip the {'s off the value by 

    string value = match.Value.Substring(1, match.Value.Length-2); 

//Then call a function which takes value and index to get the string to pass back to be susbstituted 

} 
+1

是的,但不會'行input.Replace(match.Groups [i] .Value,GetValueForIndex(i));'失敗的情況下,我將有一個形式的字符串{{intInc_G}/{intInc_G}/{YY}'。它會替換兩個子字符串的出現,而我需要只替換一個 - 在當前處理的索引處的那個。 – 2012-07-12 10:45:16

+0

是的 - 你是對的 - 我沒有允許等效的比賽 – BonyT 2012-07-12 10:49:53

+0

我已經更新了我的答案 – BonyT 2012-07-12 12:25:58

2

string.Replace會做得很好。

var updatedString = myString.Replace("{intIncG}", "something"); 

爲每個不同的字符串做一次。


更新:

既然你以產生替換字符串(如你commented),你可以使用Regex.Matches找到{指數需要的{索引 - 每個Match對象Matches集合將包含字符串中的索引。

+0

我的不好,我不能這樣做,因爲我需要知道一個特殊區域的索引,以形成一個正確的「東西」。我應該在一個問題中提到它。現在我已經添加了這個要求。抱歉。 – 2012-07-12 10:21:22

0

使用Regex.Replace

替換由正則表達式與指定的替換字符串所限定的字符圖案的所有出現。

從MSDN

0

您可以定義一個函數,並加入它的輸出 - 所以你只需要一次,而不是遍歷零件更換的每個規則。

private IEnumerable<string> Traverse(string input) 
{ 
    int index = 0; 
    string[] parts = input.Split(new[] {'/'}); 
    foreach(var part in parts) 
    { 
    index++; 
    string retVal = string.Empty; 
    switch(part) 
    { 
     case "{intIncG}": 
     retVal = "a"; // or something based on index! 
     break; 
     case "{intIncD}": 
     retVal = "b"; // or something based on index! 
     break; 

     ... 
    } 
    yield return retVal; 
    } 
} 

string replaced = string.Join("/", Traverse(inputString)); 
+0

但是不能用'{}'拆分,只能用'/'拆分? – 2012-07-12 10:52:37