Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert GroupCollection to List or IEnumerable?

Tags:

c#

Is it possible to convert a GroupCollection to a List or an IEnumerable? I'm referring to the GroupCollection in regular expressions.

like image 742
Rubans Avatar asked Mar 17 '10 18:03

Rubans


2 Answers

Sure

GroupCollection col = ...;
IEnumerable<Group> enumerable = col.Cast<Group>();
List<Group> list = col.Cast<Group>().ToList();
like image 158
JaredPar Avatar answered Oct 12 '22 13:10

JaredPar


Here's one-liner version:

new Regex("[your regex goes here]").Matches(stringThatYouAreTryingToExtractGroupsFrom)[0].Groups.Cast<Group>().Skip(1).Where(o => o.Value != "").Select(o => o.Value)

This will throw an exception if there are no matches. I am also skipping the original [0] group that captures full regex and filtering out empty groups.

like image 26
Matas Vaitkevicius Avatar answered Oct 12 '22 12:10

Matas Vaitkevicius