https://kotlinlang.org logo
#arrow
Title
# arrow
b

Benoît Liessens

11/09/2023, 8:40 AM
I’ld like to use Parsus to process a CSV like file. I setup a grammar but the parser throws a
ParseException: Unmatched token at offset=0, when expected: Token(EOF)
when I try to parse 2 lines of the CSV file. What am I missing?
Copy code
private val grammar = object : Grammar<List<Event>>() {

    val semi by literalToken(";")
    val date by regexToken("[0-9]{2}/[0-9]{2}/[0-9]{4}")
    val time by regexToken("[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}")

    val remainder by regexToken(".*\$")

    val logLine by -semi and date and -semi and time and -semi and remainder
    val newLine by regexToken("(\n|\r\n|\r)")

    override val root by parser {
        separated(logLine, newLine)()
    } map {
        it.map {
            Event(it.t1.text, it.t2.text, it.t3.text)
        }
    }
}

fun main() {
    val input =
        """;09/01/2023;21:54:51.090;other;fields;;
               |;09/01/2023;23:04:19.280;remaining stuff;
        """.trimMargin()

    val log = grammar.parseOrThrow(input)

    assertThat(log).hasSize(2)
}

data class Event(
    val date: String,
    val time: String,
    val remainder: String,
)
s

simon.vergauwen

11/09/2023, 8:54 AM
cc\\ @alllex