0

I wonder if there is a better way to parse signed integer using Sprache parser framework.

There is well known parser definition for integers without sign Parse.Number.Select(int.Parse)

But I want to parse integers with - prefix as well.

What I have got right now is Parse.Regex(@"\-?\d+").Select(int.Parse).

Is there a better way to do that without using regular expressions?

For example use Parse.Char('-').Optional() and then parse following number.

Thanks

Tadas Šukys
  • 4,140
  • 4
  • 27
  • 32

1 Answers1

7

The way I do this is similar to the following:

from op in Parse.Optional(Parse.Char('-').Token())
from num in Parse.Decimal
from trailingSpaces in Parse.Char(' ').Many()
select decimal.Parse(num) * (op.IsDefined ? -1 : 1);

Of course, leave out the trailingSpaces portion depending on the context of what you're parsing.

Geoff
  • 8,551
  • 1
  • 43
  • 50
  • Thank you @Geoff. That is (probably) what I was looking for. But... now I am meditate :) - whether your given method is "better" than mine... It is much longer and I'd say harder to read if you don't know Sprache well. Anyway, thanks. +1 – Tadas Šukys Feb 20 '14 at 13:03
  • 1
    Sure thing - and I know what you mean about being harder to read if you don't use Sprache very often. On the other hand, I don't use regular expressions very often, and I find "\-?\d+" quite non-intuitive! – Geoff Feb 20 '14 at 17:10
  • For the second line why not replace it with Parse.Number.Select(int.Parse)? Also, add '+' in?. – Gordon Feb 22 '14 at 17:44
  • Also, Geoff, is there any particular reason you are parsing whitespace there? – Gordon Feb 22 '14 at 17:50
  • @Gordon - Both the `Parse.Decimal` and the whitespace handling are there because I extracted the code from a parser project that required handling of decimals - but `Parse.Number` would work too. I leave the select to the end as it's easy to gather up the pieces found and deal with it all in one chunk; in the actual code I was instantiating a class instead, i.e. `select new DecimalExpression(...)` – Geoff Feb 24 '14 at 14:02