Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Friday, September 3, 2010 7:27 PM
Is it really this difficult to change a regex Match into an integer?
Here's my current code...
string strRepeat = m.Groups[12].ToString();
int repeat = Convert.ToInt32(strRepeat);
m.Groups[12] is always a single digit. And changing it into a string is fine, but turning it into an integer is not working. I'm getting this error.
Input string was not in a correct format.
And when I try to directly change it instead of going from a string to int, I get this error.
Unable to cast object of type 'System.Text.RegularExpressions.Group' to type 'System.IConvertible'.
How do I change this into an integer that I can use?
All replies (3)
Friday, September 3, 2010 7:47 PM âś…Answered | 1 vote
Are you sure m.Groups[12].ToString() returning valid string instead of object or etc.,. Okay debug the code and
see what is the actual value in the m.Groups[12]. Usually system will throw "Input string was not in a correct format." exception when you pass junk(other than integer) to the conversion method.
try this code and see
int repeat = 0;
Int32.TryParse(m.Groups[12].ToString(), out repeat );
if the m.groups[12] has valid value , repeat will have the converted value else 0.
Friday, September 3, 2010 7:52 PM
Yup. I miscounted twice. 13 has the valid digit.
Thanks!
Friday, September 3, 2010 7:52 PM
If you're sure it's always a number, you can also just use int.Parse()