Counting regex expressions

  • Thread starter Thread starter trashman.horlicks
  • Start date Start date
T

trashman.horlicks

Hi,
I'm getting into a tangle with Regex in C#.

If I had an expression like abc[1].def[2].ghi[3] etc.

How do I count how many instances there are of "[ ]" and "."

Thanks a lot!

TH
 
If I had an expression like abc[1].def[2].ghi[3] etc.

How do I count how many instances there are of "[ ]" and "."

Use the regex @" \[ \s* \d+ \s* \] " with the IgnorePatternWhitespace
option; call Matches; and read the Count property.
 
Jon said:
If I had an expression like abc[1].def[2].ghi[3] etc.

How do I count how many instances there are of "[ ]" and "."

Use the regex @" \[ \s* \d+ \s* \] " with the IgnorePatternWhitespace
option; call Matches; and read the Count property.

Could I do it like this?

// Assume Key is of the form a.b.c.d.e.f

Match n = Regex.Match( key, @"\." );

int noOfMatches = n.Count;
 
Could I do it like this?

// Assume Key is of the form a.b.c.d.e.f

Match n = Regex.Match( key, @"\." );

int noOfMatches = n.Count;

Not quite - the Match object represents a single match, and doesn't
have a Count property. You want the Matches method, not the Match
method:

int NumberOfDots = Regex.Matches(Key, @"\.").Count;
 
Back
Top