「特別な領域」が中括弧で囲まれている文字列があります。
{intIncG}/{intIncD}/02-{yy}
{}の間でこれらすべての要素を繰り返し処理し、コンテンツに基づいてそれらを置き換える必要があります。C#でそれを行うための最良のコード構造は何ですか?
正しい値に置き換えるには、各「特殊領域{}」のインデックスを知る必要があるため、単に置き換えることはできません。
「特別な領域」が中括弧で囲まれている文字列があります。
{intIncG}/{intIncD}/02-{yy}
{}の間でこれらすべての要素を繰り返し処理し、コンテンツに基づいてそれらを置き換える必要があります。C#でそれを行うための最良のコード構造は何ですか?
正しい値に置き換えるには、各「特殊領域{}」のインデックスを知る必要があるため、単に置き換えることはできません。
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 回トラバースするだけで済みます。
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));