2012-08-07 142 views
1

我想在運行時基於一組花括號內的內容替換字符串中的值。將正則表達式結果傳遞給函數

// 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」

回答

3

您可以將代理傳遞給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); 
+0

非常好,不得不從{m.Groups [1] .Value'中刪除{},但除此之外它效果很好。 – JConstantine 2012-08-07 13:34:46

+0

這有點奇怪,因爲這在我的機器上運行良好。你使用相同的正則表達式嗎?如果我調用'Regex.Replace(「/ accounts/{accountId}」,@「\ {(。*?)\}」,GetValueForFieldNamed)',那麼在'GetValueForFieldNamed'裏面我有'm.Groups [0] .Value ==「{accountID}」',但是'm.Groups [1] .Value ==「accountID」'。 – Jan 2012-08-07 13:46:21

+0

這是我的錯誤,我使用索引0而不是1.出於好奇,爲什麼它會給出2個結果? – JConstantine 2012-08-07 14:05:16

1

在你的模式中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

相關問題