【问题标题】:How to get value in dictionary from 2 different string [duplicate]如何从2个不同的字符串中获取字典中的值[重复]
【发布时间】:2019-05-24 05:33:21
【问题描述】:

我有 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/"

【问题讨论】:

  • 你能不能简短一点,什么都不懂,请尽快编辑,否则问题将被降级并被删除。
  • 我已经编辑了一些我的问题。

标签: c# regex string


【解决方案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 不包含相同数量的部分。

【讨论】:

  • 感谢您回复我,我已经编辑了一些我的问题
  • @ShivangGupta 答案仍然有效
  • 我们可以通过正则表达式来做到这一点吗?哪个是更好的正则表达式或上述一个?
  • 我会说上面一个,因为正则表达式用于解析单个字符串(一次一个字符串),而不是多个字符串。
【解决方案2】:

这是一个正则表达式解决方案,但您需要稍微更改模板。

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 解析器而不是使用正则表达式。

【讨论】:

  • 感谢您回复我,我已经编辑了一些我的问题
猜你喜欢
  • 2018-09-27
  • 2012-03-24
  • 2021-11-09
  • 2020-12-27
  • 2020-04-04
  • 2020-09-03
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
相关资源
最近更新 更多