I have the expression already written, but whenever I run the code I get the entire string and a whole bunch of null values:
Regex regex = new Regex(@"y=\([0-9]\)\([0-9]\)(\s|)\+(\s+|)[0-9]");
Match match = regex.Match("y=(4)(5)+6");
for (int i = 0; i < match.Length; i++)
{
MessageBox.Show(i+"---"+match.Groups[i].Value);
}
Expected output: 4, 5, 6 (in different MessageBoxes
Actual output: y=(4)(5)+6
It finds if the entered string is correct, but once it does I can’t get the specific values (the 4, 5, and 6). What can I do to possibly get that code? This is probably something very simple, but I’ve tried looking at the MSDN match.NextMatch article and that doesn’t seem to help either.
Thank you!
As it currently is, you don’t have any groups specified. (Except for around the spaces.)
You can specify groups using parenthesis. The parenthesis you are currently using have backslashes, so they are being used as part of the matching. Add an extra set of parenthesis inside of those.
Like so:
And with spaces:
This will also allow for spaces between the parts to be optional, since * means 0 or more. This is better than (?:\s+|) that was given above, since you don’t need a group for the spaces. It is also better since the pipe means ‘or’. What you are saying with \s+| is “One or more spaces OR nothing”. This is the same as \s*, which would be “Zero or more spaces”.
Also, I used [0-9]+, because that means 1 or more digits. This allows numbers with multiple digits, like 10 or 100, to be matched. And another side note, using [0-9] is better than \d since \d refers to more than just the numbers we are used to.