简体   繁体   中英

Sprache: parse signed integer

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM