Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# regex captures

I am matching a repeating group that contains a mixture of optional and non-optional groups. When I iterate over the captures, the capture collections are always collapsed, i.e. they do not insert a null element for the non matched items.

Is there a way to preserve the order of matches in capture collections, such that any omitted optional item is inserted as null, thereby ensuring capture collection elements correspond across groups?

To clarify, let's say my repeating (parent) group is matched three times, and in one of the three matches an optional child group was omitted but was present in the other two groups, I end up with a capture collection for the child group which is one element less than the other capture collections. How do I know which of the parent groups omitted the optional item?

I suppose it would be possible to use the Index property of the capture collection item and check whether it falls within the bounds of the parent group, but it would be easier if non-matches returned a null item in the capture collection. Is there a way to achieve this?

like image 960
greenback Avatar asked Oct 18 '12 18:10

greenback


1 Answers

Instead of (pattern)? use (pattern|) and you should get what you want...

like image 50
Ωmega Avatar answered Oct 11 '22 04:10

Ωmega