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)
Regex有一个带有MatchEvaluator的重载.输入是Match,它返回一个字符串.在这种情况下匹配的值将是整个令牌,因此您可以创建一个提取值的垫片(您已经在正则表达式中捕获它)并适应您发布的方法.
Regex.Replace(inputString,
tokenMatchRegexString,
match => TokenReplacement(match.Groups[1].Value));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4192 次 |
| 最近记录: |