vinczemarton
vinczemarton

Reputation: 8156

Parse 2 numbers in C# divided by minus sign

I have to parse a string. It contains one or two numbers.

It can has 3 froms.

  1. {number1}-{number2}
  2. {number1}-
  3. -{number2}

The numbers can be negative.

So for example:

now the harder part:

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

Answers (3)

Michael Edenfield
Michael Edenfield

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

Alex Peta
Alex Peta

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

dtb
dtb

Reputation: 217351

Have you considered using a regular expression?

^(-?\d+)?-(-?\d+)?$

Upvotes: 6

Related Questions