Reputation: 4220
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
Upvotes: 1
Views: 1834
Reputation: 8850
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.
Upvotes: 9