Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Building parsers for fixed-width fields #24

Open
KushalP opened this issue Apr 28, 2020 · 1 comment
Open

Building parsers for fixed-width fields #24

KushalP opened this issue Apr 28, 2020 · 1 comment

Comments

@KushalP
Copy link

KushalP commented Apr 28, 2020

Let's say I have a String containing numbers that I want to convert into a data class. The fields are of fixed width. How should I go about building a grammar that can achieve this without having the different tokens cause issues with each other?

At the moment I'm seeing a MismatchedToken exception.

Reproducible sample case

data class Line(
    val fieldA: Int,
    val fieldB: Int,
    val fieldC: Int
)

object LineGrammar : Grammar<Line>() {
    private val fieldA by token("[0-9]{2}")
    private val fieldB by token("[0-9]{5}")
    private val fieldC by token("[0-9]{3}")

    private val line =
        fieldA and fieldB and fieldC

    override val rootParser: Parser<Line> =
        line.map { (a, b, c) ->
            Line(
                fieldA = a.text.toInt(),
                fieldB = b.text.toInt(),
                fieldC = c.text.toInt()
            )
        }
}

val line = "1234567891"
val result = LineGrammar.parseToEnd(line)
// result should be Line(fieldA = 12, fieldB = 34567, fieldC = 891)
//
// Instead seeing the following exception
// Could not parse input: MismatchedToken(expected=fieldB ([0-9]{5}), found=fieldA for "34" at 2 (1:3))
// com.github.h0tk3y.betterParse.parser.ParseException: Could not parse input: MismatchedToken(expected=fieldB ([0-9]{5}), found=fieldA for "34" at 2 (1:3))
// 	at com.github.h0tk3y.betterParse.parser.ParserKt.toParsedOrThrow(Parser.kt:70)
// 	at com.github.h0tk3y.betterParse.parser.ParserKt.parseToEnd(Parser.kt:30)
// 	at com.github.h0tk3y.betterParse.grammar.GrammarKt.parseToEnd(Grammar.kt:69)
@tcoopman
Copy link

Ran into the same issue. Did you ever find a solution for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants