Reputation: 93
I've tested my regex in a regex tester and the statement itself appears that it should be working, however instead of matching 4 objects as it should, it only matches 1 (the entire string) which I'm not sure why its even doing that...
rgx = new Regex(@"^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$");
matches = rgx.Matches("0.0.0.95");
at this point if I do:
foreach (Match m in matches)
{
Console.WriteLine(m.Value);
}
it will just show "0.0.0.95" when it should be matching 0, 0, 0, and 95 and not the entire string. What am I doing wrong here?
ANSWER - The single match of the entire string contained the group matches I was looking for, accessed in this manner:
r.r1 = Convert.ToInt32(m.Groups[1].Value);
r.r2 = Convert.ToInt32(m.Groups[2].Value);
r.r3 = Convert.ToInt32(m.Groups[3].Value);
r.r4 = Convert.ToInt32(m.Groups[4].Value);
Upvotes: 1
Views: 51
Reputation: 726709
In this case you don't get multiple matches - there is only one match in there, but it has four capturing groups:
^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$
// ^^^^^^^^ ^^^^^^^^ ^^^^^^^^ ^^^^^^^^
// Group 1 Group 2 Group 3 Group 4
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Group 0
There is a special group number zero that includes the entire match.
So you need to modify your program like this:
Console.WriteLine("One:'{0}' Two:'{1}' Three:'{2}' Four:'{3}'"
, m.Groups[1].Value
, m.Groups[2].Value
, m.Groups[3].Value
, m.Groups[4].Value
);
Upvotes: 3