我有一個字符串,其中「特殊區域」括在大括號來改寫的字符串:如何通過模式
{intIncG}/{intIncD}/02-{yy}
我需要的基礎上,通過所有這些元素其間{的迭代}和替換它們關於他們的內容。什麼是最好的代碼結構在C#中做到這一點?
我不能只是做一個替換,因爲我需要知道每個「speacial area {}」的索引,以便用正確的值替換它。
我有一個字符串,其中「特殊區域」括在大括號來改寫的字符串:如何通過模式
{intIncG}/{intIncD}/02-{yy}
我需要的基礎上,通過所有這些元素其間{的迭代}和替換它們關於他們的內容。什麼是最好的代碼結構在C#中做到這一點?
我不能只是做一個替換,因爲我需要知道每個「speacial area {}」的索引,以便用正確的值替換它。
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
}
您可以定義一個函數,並加入它的輸出 - 所以你只需要一次,而不是遍歷零件更換的每個規則。
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));
但是不能用'{}'拆分,只能用'/'拆分? – 2012-07-12 10:52:37
所以拆分或更換? – sll 2012-07-12 10:18:27
只是索引?您不會根據{}內的內容更改替換項嗎? – BonyT 2012-07-12 10:22:18
兩者都需要考慮 - 索引和內容 - 實際代碼。 – 2012-07-12 10:46:46