Anlo
Anlo

Reputation: 3266

Regex: Keep all captures, not just the last repetition

I'm having a C# regex problem. The solution is probably very easy, but I just can't get it to work right now.

string type = "ARRAY [0..10,0..20,1..2] OF INT";
Regex regex = new Regex(@"^ARRAY \[(?:(\d+)\.\.(\d+),?)+\]");
var matches = regex.Matches(type);

This code captures only "1" and "2", which is the bounds of the last dimension of the array. I need to capture all dimensions, preferably in the nested format {{0,10},{0,20},{1,2}} but since there will always be two captures for each dimension, the flat format {0,10,0,20,1,2} will do as well.

Upvotes: 0

Views: 108

Answers (3)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51390

You already have it in the match data, in Captures:

match.Group[1]
     .Captures
     .Cast<Capture>()
     .Select(capture => int.Parse(capture.Value))
     .Zip(match.Group[2]
               .Captures
               .Cast<Capture>()
               .Select(capture => int.Parse(capture.Value)),
         (min, max) => new { min, max })

Each group exposes a collection of Captures that will contain all the instances that matched.

match.Group[1].Captures contains all of the min values, while match.Group[2].Captures contains all of the max values. The code above simply zips them together to produce the output you need.

Upvotes: 2

SierraOscar
SierraOscar

Reputation: 17637

Regex regex = new Regex(@"^ARRAY \[([\d]+[.]{2}[\d]+[,]?)+\]")

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174756

\G assert position at the end of the previous match or the start of the string for the first match.

(?:^ARRAY \[|\G),?(\d+)\.\.(\d+)

DEMO

Upvotes: 2

Related Questions