C#Regex:如何使用在运行时生成的字符串替换标记?

Jim*_* G. 2 regex token capture-group c#-3.0

给定以下输入和正则表达式字符串:

const string inputString = "${Principal}*${Rate}*${Years}";
const string tokenMatchRegexString = @"\${([^}]+)}";
Run Code Online (Sandbox Code Playgroud)

如何用我的'ReplaceToken'函数的返回值替换每个标记(即$ {Principal},$ {Rate}和$ {Years})?

private static string ReplaceToken(string tokenString)
{
    switch (tokenString)
    {
        case "Principal":
            return GetPrincipal();
        case "Rate":
            return GetRate();
        case "Years":
            return GetYears();
        default:
            throw new NotImplementedException(String.Format("A replacment for the token '{0}' has not been implemented.", tokenString));
    }
}

private static string GetPrincipal()
{
    throw new NotImplementedException();
}

private static string GetRate()
{
    throw new NotImplementedException();
}

private static string GetYears()
{
    throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)

Der*_*ger 7

Regex有一个带有MatchEvaluator的重载.输入是Match,它返回一个字符串.在这种情况下匹配的值将是整个令牌,因此您可以创建一个提取值的垫片(您已经在正则表达式中捕获它)并适应您发布的方法.

Regex.Replace(inputString,
              tokenMatchRegexString,
              match => TokenReplacement(match.Groups[1].Value));
Run Code Online (Sandbox Code Playgroud)