scalaparser-combinatorsfastparse

How to match exactly 'n' given characters with FastParse


The FastParse parser-combinator scala library gives you the .rep(n) 'Repeat' method to allow you to create a new parser that attempts to parse the givenParser n or more times. What's the canonical way to do this if I want exactly n matches?

In my case, I want to parse a 40-character Git commit id - if it were longer than 40 characters, that's not a commit id, and it shouldn't be a match.

The closest example I've found in docs so far is:

val unicodeEscape = P( "u" ~ hexDigit ~ hexDigit ~ hexDigit ~ hexDigit )

...which matches 4 characters with simple repetition (verbose for a 40-character commit id).

These are parser-combinators, not regex, where the answer would be something like \p{XDigit}{40}.


Solution

  • Since the issue was closed by this commit, rep supports a max keyword argument. It also now supports an exactly keyword argument.

    hexdigit.rep(exactly = 40)