-1

I have 2 string

string str="nl/vacature/admin/Employee/home/details/"

and other one

string template ="nl/vacature/{model}/{controller}/{Action}/{Method}/"

I am looking for

model=admin,controller=Employee,Action=home,Method=details

in an object or in dictionary in key-value format.Their URL and template key may be at different order it may be

string template ="vacature/jobcount/{controller}/{Action}/{model}/{Method}/"

string str ="vacature/jobcount/Employee/home/admin/details/"

2 Answers2

1

Here's a Regex solution, but you need to change the template a little bit.

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" } }

However, external parsing library might be a better fit. You can find some URL parser instead of using regex.

SGKoishi
  • 390
  • 2
  • 11
1

Try this:

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]);
}

I leave to you exception handling in case, that URLs won't consist of the same number of parts.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69