これを試して:
Regex rx = new Regex("a|b|c");
string str = "abc";
MatchEvaluator matcher = match => {
string value = match.Value;
if (value == "a") {
return "6b";
} else if (value == "b") {
return "7c";
} else {
return "8d";
}
};
var str2 = rx.Replace(str, matcher);
正規表現を使用したくない場合は、次のようにします。
static void Main(string[] args)
{
var replacements = new[] {
new Tuple<string, string>("a", "6b"),
new Tuple<string, string>("b", "6c"),
new Tuple<string, string>("c", "6a")
};
string str = "adbc";
var str2 = MultipleReplace(str, replacements);
}
static string MultipleReplace(string str, IEnumerable<Tuple<string, string>> replacements) {
StringBuilder str2 = new StringBuilder();
for (int i = 0; i < str.Length; i++) {
bool found = false;
foreach (var rep in replacements) {
if (str.Length - i >= rep.Item1.Length && str.Substring(i, rep.Item1.Length) == rep.Item1) {
str2.Append(rep.Item2);
i += rep.Item1.Length - 1;
found = true;
break;
}
}
if (!found) {
str2.Append(str[i]);
}
}
return str2.ToString();
}