我有2个字符串
string str="nl/vacature/admin/Employee/home/details/"
和另一个
string template ="nl/vacature/{model}/{controller}/{Action}/{Method}/"
我在寻找
model=admin,controller=Employee,Action=home,Method=details
在对象或字典中为键-值格式。其URL和模板键的顺序可能不同
string template ="vacature/jobcount/{controller}/{Action}/{model}/{Method}/"
string str ="vacature/jobcount/Employee/home/admin/details/"
答案 0 :(得分:1)
这是Regex解决方案,但是您需要稍微更改一下模板。
string url = "nl/vacature/admin/Employee/home/details/";
string template = "nl/vacature/(?<Model>.*?)/(?<Controller>.*?)/(?<Action>.*?)/(?<Method>.*?)/";
var matches = Regex.Match(url, template).Groups.Cast<Group>().Where(g => !int.TryParse(g.Name, out _)).ToDictionary(m => m.Name, m => m.Value);
// Dictionary<string, string>(4) { { "Model", "admin" }, { "Controller", "Employee" }, { "Action", "home" }, { "Method", "details" } }
但是,外部解析库可能更合适。您可以找到一些URL解析器,而不使用正则表达式。
答案 1 :(得分:1)
尝试一下:
string url = "nl/vacature/admin/Employee/home/details/";
string template = "nl/vacature/{model}/{controller}/{Action}/{Method}/";
// remove unnecessary parts
template = template.Replace("nl/vacature/", "").Replace("{", "").Replace("}", "");
url = url.Replace("nl/vacature/", "");
// dictionary, that will hold pairs, that you want
var dict = new Dictionary<string,string>();
var urlList = url.Split('/');
var templateList = template.Split('/');
for(int i = 0; i < urlList.Length; i++)
{
dict.Add(templateList[i], urlList[i]);
}
如果URL不会包含相同数量的部分,我会为您提供异常处理。