简体   繁体   English

如何使用正则表达式比较两个列表?

[英]How To Compare Two Lists Using Regex?

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. 第二个列表与第一个列表基本相同,但它没有ID。 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:) 我有一个正则表达式(@"(?<=\\(ID:)[0-9]+");这只返回里面的数字(ID :)

I want to compare these two Lists based on this RegEX, Where, I want only the ID's of the selected items. 我想基于此RegEX比较这两个列表,其中,我只想要所选项目的ID。

For Ex: If DM-0061 is selected i'll get 225 . 例如:如果选择了DM-0061 ,我将获得225

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: 命名的捕获组key包括:
    • Any character any number of repetitions, but as few as possible 任何字符任意数量的重复,但尽可能少
  • Whitespace 空白
  • Literal (ID: 文字(ID:
  • A named capture group value consisting of: 命名的捕获组value包含:
    • 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 实例: http//rextester.com/PMTUFW14656

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM