Skip to main content
 首页 » 编程设计

c#之将 Regex 结果传递给函数

2024年02月20日22findumars

我正在尝试根据一组大括号中的内容在运行时替换字符串中的值。

// 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);