regex - C#正则表达式:如何用运行时生成的字符串替换 token ?

标签 regex c#-3.0 token capture-group

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

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

如何用'ReplaceToken'函数的返回值替换每个 token (即$ {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();
}

最佳答案

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

Regex.Replace(inputString,
              tokenMatchRegexString,
              match => TokenReplacement(match.Groups[1].Value));

关于regex - C#正则表达式:如何用运行时生成的字符串替换 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1869567/

相关文章:

javascript - 字符串上的正则表达式或 For 循环 - 拆分和连接

c# - 传递 Func<TSource, TKey> keySelector 错误

android - 年龄的谷歌登录请求不起作用

Python 使用验证 token 向网站请求 GET 和 POST

python - 如何在 Python 中使用 RegEx 选择简短的 Cisco 接口(interface)名称?

REGEX 在空格之间提取字符串

javascript - 如果表情符号是国旗,则使用正则表达式进行检测

c# - 在 C# 中的 lambda 表达式中应用多个条件

c#-3.0 - 有没有更好的方法在 C#3.0 中编写这行 C# 代码?

javascript - Angular js : $locationChangeStart checking token