Reputation: 8156
I have to parse a string. It contains one or two numbers.
It can has 3 froms.
The numbers can be negative.
So for example:
now the harder part:
-100--200 means: number1 = -100, number2 = -200
-100-200- means: throw new FormatException(). its not a valid string.
Anything that cannot be parsed as 2 ints throws a formatexception (int.Parse does this, so it can be depended on).
I need a parser to parse it to two int? -s (nullable ints).
Every string is either valid (it makes sense), or invalid (it does not makes sense). There is no string that can mean 2 things (at least I didn't find one).
If I het the 2 value, I want it to return in a tuple.
I get tangled up in the ifs.
Upvotes: 2
Views: 520
Reputation: 28338
(Editing to add the updated regex from the comments)
It seems like you could use the Regex class to figure this out, since your syntax is fairly regular and structures:
var regex = new Regex(@"^(?<first>-?[\d.,]+)?-(?<second>-?[\d.,]+)?$");
var match = regex.Match(input);
if (match.Success)
{
int? a = match.Groups["first"].Success
? Int32.Parse(match.Groups["first"].Value)
: (int?)null;
int? b = match.Groups["second"].Success
? Int32.Parse(match.Groups["second"].Value)
: (int?)null;
}
Upvotes: 8
Reputation: 1407
you could try .Split() method:
string testString = "100-200" ;
string[] results = testString.Split('-');
int nr1;
int nr2;
try
{
nr1 = Convert.toInt32(results[0]);
nr2 = Convert.toInt32(results[1]);
}
catch{}
Upvotes: -2