Hi
I am doing Regular expressions right now in C# and I don't understand which Collection should I be using?
Like I seen a couple different tutorials some Using MatchCollection and some using GroupCollection. I don't know when I should be using what.
Like Here are some ways I seen to do it.
// This is my own try at it.
Code:
string asinPattern = "reg Expression Here;
Regex MyRegex = new Regex(asinPattern,
RegexOptions.IgnoreCase
| RegexOptions.Multiline
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
MatchCollection matchAsin = MyRegex.Matches(result);
for (int i = 0; i < matchAsin.Count; i++)
{
// Group g = matchAsin[i];
Match g = matchAsin[i];
Test.Add(g.Value);
}
So first what Is the difference between using Group or Match. They both seem to get the same result.
The second way I see it is with a for each loop.
Code:
MatchCollection matches = rx.Matches(text);
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
Console.WriteLine("'{0}' repeated at positions {1} and {2}",
groups["word"].Value,
groups[0].Index,
groups[1].Index);
}
So this one I don't understand why they first put in a match collection then a groupCollection. It seems kinda pointless to me. To keep put it in a another collection one at a time. So I got to be missing something.
http://msdn.microsoft.com/en-us/libr...ollection.aspx
Then finally I seen
Code:
using System.Text.RegularExpressions;
class Reg{
public static void Main(){
// Should match everything except the last two.
string str = "$1.57 $316.15 $19.30 $0.30 $0.00 $41.10 $5.1 $.5";
string strMatch = @"\$(\d+)\.(\d\d)";
for ( Match m = Regex.Match( str, strMatch ); m.Success; m = m.NextMatch() ){
GroupCollection gc = m.Groups;
System.Console.WriteLine( "The number of captures: " + gc.Count );
// Group 0 is the entire matched string itself
// while Group 1 is the first group to be captured.
for ( int i = 0; i < gc.Count; i++ ){
Group g = gc[i];
System.Console.WriteLine( g.Value );
}
}
}
}
Where they use Group and GroupCollection.
So when should I use each scenario?
Thanks