问题
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.
回答1:
If you use a regular expression such as:
(?<key>.*?)\s\(ID:(?<value>[0-9]+)\)
This regex translates to
- A named capture group
keyconsisting of:- Any character any number of repetitions, but as few as possible
- Whitespace
- Literal
(ID: - A named capture group
valueconsisting 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