我有一个类似的url
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]]; });