我正在尝试根据一组大括号中的内容在运行时替换字符串中的值。
// this.LinkUrl = "/accounts/{accountId}"
this.LinkUrl = Regex.Replace(account.Company.LinkUrl, @"\{(.*?)\}", "$1");
// this.LinkUrl = "/accounts/accountId"
到目前为止,它按预期工作并删除了大括号。但是我怎样才能将 $1 值传递给函数,就像这样
this.LinkUrl = Regex.Replace(account.Company.LinkUrl, @"\{(.*?)\}", this.GetValueForFieldNamed("$1"));
所以“accountid”被替换为函数返回的值?例如“/账户/56”
最佳答案
您可以将委托(delegate)传递给 Regex.Replace
方法,该方法采用 Match
并返回一个字符串,例如定义替换函数:
string GetValueForFieldNamed(Match m){
string res = m.Groups[1].Value;
//do stuff with res
return res;
}
然后这样调用它:
LinkUrl = Regex.Replace(account.Company.LinkUrl, @"\{(.*?)\}", GetValueForFieldNamed);
关于c# - 将 Regex 结果传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11846528/