簡體   English   中英

用正則表達式動態替換值

[英]Replace value dynamically with regular expression

我有一個網址

http://www.somesite.com/$(someKey).php

我有一個包含這些鍵的字典,我需要使用Regex將$(*)替換為該鍵標記的字典中的值。

我怎樣才能做到這一點?

您可以使用Regex.Replace方法 嘗試這個:

class Program
{
    static void Main(string[] args)
    {
        var dict = new Dictionary<string, string>();
        dict.Add("someKey1", "MyPage1");
        dict.Add("someKey2", "MyPage2");

        var input = "http://www.somesite.com/$(someKey2).php";
        var output = Regex.Replace(input, @"\$\((.*?)\)", m => 
        {
            return dict[m.Groups[1].Value];
        });
    }
}

像這樣的事情:

url = Regex.Replace(url , @"\$\(([^)]+)\)", delegate(Match m){ return dict[m.Groups[1]]; });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM