How To Compare Two Lists Using Regex?

試著忘記壹切 提交于 2021-02-08 09:32:43

问题


I Have Two Lists,

  1. List<string>IDList //DM-0016 (ID:225),LPG Test (ID:232), 18S1(ID:290)..
  2. List<string>Names // DM-0016,LPG Test, 18S1..

The Second List is basically the same as the First but it doesn't have the IDs. I am Showing the Second List in a Multiple Choice Dialog, Where, user can select multiple items.

I have a Regular Expression (@"(?<=\(ID:)[0-9]+"); This returns only the the number inside (ID:)

I want to compare these two Lists based on this RegEX, Where, I want only the ID's of the selected items.

For Ex: If DM-0061 is selected i'll get 225.


回答1:


If you use a regular expression such as:

(?<key>.*?)\s\(ID:(?<value>[0-9]+)\)

This regex translates to

  • A named capture group key consisting of:
    • Any character any number of repetitions, but as few as possible
  • Whitespace
  • Literal (ID:
  • A named capture group value consisting of:
    • Any number, one or more repetitions
  • Literal )

You can project your original list to a dictionary and easily use it as a lookup:

var list = new List<string>(){
    "DM-0016 (ID:225)","LPG Test (ID:232)", "18S1 (ID:290)"
};
var regex = new Regex(@"(?<key>.*?)\s\(ID:(?<value>[0-9]+)\)");

var dict = list.Select(i => regex.Match(i))
               .ToDictionary(
                    k => k.Groups["key"].Value, 
                    v => v.Groups["value"].Value);

Console.WriteLine(dict["DM-0016"]); // writes 225

Live example: http://rextester.com/PMTUFW14656



来源:https://stackoverflow.com/questions/51555021/how-to-compare-two-lists-using-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!