给定以下输入和正则表达式字符串:
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/