如何使用正则表达式比较两个列表? [英] How To Compare Two Lists Using Regex?
问题描述
我有两个列表,
-
List< string> IDList//DM-0016(ID:225),LPG测试(ID:232),18S1(ID:290)..
-
列表< string>名称//DM-0016,LPG测试,18S1 ..
第二个列表与第一个列表基本相同,但是没有ID.我在多项选择"对话框中显示第二个列表,用户可以在其中选择多个项目.
我有一个正则表达式(@(?< = \(ID:)[0-9] +");
这仅返回(ID :)内部的数字>
我想基于此RegEX比较这两个列表,在这里,我只想要所选项目的ID.
例如::如果选择了 DM-0061 ,我将得到 225 .
如果使用正则表达式,例如:
(?< key>.*?)\ s \(ID:(?< value> [0-9] +)\)
此正则表达式翻译为
- 命名捕获组
key
,由以下内容组成:- 任何字符均可重复多次,但应尽可能少
- 空白
- 文字
(ID:
- 一个命名的捕获组
value
,包括:- 任何数字,一个或多个重复
- 文字
)
您可以将原始列表投影到字典中,并轻松地将其用作查找:
var list = new List< string>(){"DM-0016(ID:225)","LPG测试(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"]);//写225
实时示例: http://rextester.com/PMTUFW14656
I Have Two Lists,
List<string>IDList //DM-0016 (ID:225),LPG Test (ID:232), 18S1(ID:290)..
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.
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
这篇关于如何使用正则表达式比较两个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!