scalafastparse

fail on match in scala fastparse


I have the following fastparse parser named "variable":

val alphabet = 'A' to 'z'
val variable: Parser[String] = P(CharsWhileIn(alphabet).!)

I would like for this parser to fail on a specific word like "end", while still returning a Parser[String].


Solution

  • Try with negative lookahead:

    val alphabet = 'A' to 'Z'
    val variable: P[String] = P(!"end" ~ CharIn(alphabet).rep(min = 1)).!
    

    where this will succeed:

    println( variable.parse("ABCend") )   // Success(ABC,3)
    

    but this won't:

    println( variable.parse("endABC") )   // Failure(!("end"):1:4 ..."ABC")