How to parse real numbers? #237
-
Hi. I am trying to implement a parser of positive real numbers. The format is expressed in regular expressions as follows:
My attempt: pub fn real_number() -> impl Parser<char, Token, Error = Simple<char>> {
text::int(10)
.chain::<char, _, _>(
just('.').chain(
text::digits(10)
.chain(
one_of("eE")
.chain(just('-'))
.or_not()
.flatten()
.chain(text::digits(10)),
)
.or_not()
.flatten(),
),
)
.or_not()
.flatten()
.collect::<String>()
.map(Token::RealNumber) // enum Token{ RealNumber(String) }
} I'm still unfamiliar with // get "123."
real_number().parse("123.456")
// get "0."
real_number().parse("0.1E5") I wonder how to correctly build the parser. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I think you're fairly close with this as-is. You might find the number parser in the Lexing tokens like this is definitely the sort of thing that's currently a bit verbose in chumsky today. This will be improving though! The soon-to-be-merged |
Beta Was this translation helpful? Give feedback.
I think you're fairly close with this as-is. You might find the number parser in the
json.rs
example to be useful, it pretty much does what you're looking for.Lexing tokens like this is definitely the sort of thing that's currently a bit verbose in chumsky today. This will be improving though! The soon-to-be-merged
zero-copy
branch will include a regex combinator, allowing you to parse something like this in a single line!