Regular expression groupings/collections

  • Thread starter Michael Russell
  • Start date
M

Michael Russell

Hi,
I'm having trouble retrieving matches from strings using regular
expressions. I'm parsing a string that's a date with either a 2 or 4
digit year (ex. "1/15/2005"). The RegExp object is created as such:

m_rx = new Regex( @"^(\d{1,2})/(\d{1,2})/(\d{2,4})$",
RegexOptions.IgnoreCase );

What I want to be able to do is retrieve separately the day, month, and
year. When I do "m_rx.Matches( text )" for the above date, I get a
Match. However, I only get one Match, and that match only has 1 Group,
which in turn only has one item in its CaptureCollection. To verify
this, I tried the following:

Group g = matches[ 0 ];
CaptureCollection cc = g.Captures;
Console.WriteLine( "Num matches: {0}", matches.Count );
Console.WriteLine( "Num Collections: {0}", g.Captures.Count );
Console.WriteLine( "Num items: {0}, {1}", cc.Count, cc[ 0 ].Value );

I expected to be able to access each capture by using something like
"cc[0].Value".

The first item in each (Match, Group, Capture) is always the original
string, as I would expect. So my question becomes: Is my pattern
wrong, or am I looking in the wrong place for the values?

Thanks,
Michael
 
M

Markus Stoeger

Michael said:
So my question becomes: Is my pattern wrong, or am I looking in the
wrong place for the values?

I only added "named groups" to your pattern and it seems to work:

string pattern =@"^(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})$";
Regex re = new Regex(pattern, RegexOptions.IgnoreCase);

Match m = re.Match("1/15/2005");

if (m.Success) {
int day = int.Parse(m.Groups["day"].Value);
int month = int.Parse(m.Groups["month"].Value);
int year = int.Parse(m.Groups["year"].Value);

Trace.WriteLine(day + ", " + month + ", " + year);
}

hth,
Max
 
M

Michael Russell

Markus said:
Michael said:
So my question becomes: Is my pattern wrong, or am I looking in the
wrong place for the values?

I only added "named groups" to your pattern and it seems to work:

string pattern =@"^(?<month>\d{1,2})/(?<day>\d{1,2})/(?<year>\d{2,4})$";
Regex re = new Regex(pattern, RegexOptions.IgnoreCase);

Match m = re.Match("1/15/2005");

if (m.Success) {
int day = int.Parse(m.Groups["day"].Value);
int month = int.Parse(m.Groups["month"].Value);
int year = int.Parse(m.Groups["year"].Value);

Trace.WriteLine(day + ", " + month + ", " + year);
}

hth,
Max

Thanks Max, turns out I was expecting (wrongly) multiple matches,
instead of a single match with multiple captures. I adjusted to match
your code (without the named groups) and it worked perfectly.

Michael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top