将正则表达式结果传递给函数
问题描述:
我想在运行时基于一组花括号内的内容替换字符串中的值。将正则表达式结果传递给函数
// 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”
答
您可以将代理传递给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);
答
在你的模式中1st
正则表达式组将是你想要的ID
,所以你希望将其存储在一个变量,然后再使用GetValueForFieldNamed()
功能并用返回值替换id
:
var match = Regex.Match(account.Company.LinkUrl, @"\{(.*?)\}");
if (match.Success) {
string id = match.Groups[1].Value;
this.LinkUrl = Regex.Replace(account.Company.LinkUrl, String.Format(@"\{({0})\}", id), this.GetValueForFieldNamed(id));
}
+0
虽然我没有具体说明,它可以包含多个{}值,这个答案将工作的单一解决方案。所以谢谢。 – JConstantine 2012-08-07 13:34:06
非常好,不得不从{m.Groups [1] .Value'中删除{},但除此之外它效果很好。 – JConstantine 2012-08-07 13:34:46
这有点奇怪,因为这在我的机器上运行良好。你使用相同的正则表达式吗?如果我调用'Regex.Replace(“/ accounts/{accountId}”,@“\ {(。*?)\}”,GetValueForFieldNamed)',那么在'GetValueForFieldNamed'里面我有'm.Groups [0] .Value ==“{accountID}”',但是'm.Groups [1] .Value ==“accountID”'。 – Jan 2012-08-07 13:46:21
这是我的错误,我使用索引0而不是1.出于好奇,为什么它会给出2个结果? – JConstantine 2012-08-07 14:05:16