Question

I have the following simple Scala Parser:

object MainTest extends JavaTokenParsers {
  def line: Parser[String] = "A"
  def main(args: Array[String]): Unit = {
    println(parseAll(line, """AB""".stripMargin))
  }
}

I would like this to process one line (in this case "AB") and returns an error if the line is not equal to "A" (or any other pattern I give).

Unfortunately this fails with:

[1.2] failure: string matching regex `\z' expected but `B' found

AB
 ^

The problem is that 'A' is matched even if end of the line is not reached. I've would like to make the parser fail for ALL the 'AB' line, so that if I split the input in lines an entire line is either matched or not.

Is it possible?

Was it helpful?

Solution

Your parser works. You just need to catch the result instead of sending it to println. 'A' is matched, but 'B' is not (since '\z'='end of input' was expected) which makes the whole match unsuccessful.

import scala.util.parsing.combinator.JavaTokenParsers

object MainTest extends JavaTokenParsers {
  def line: Parser[String] = "A"                     
  def main: Unit = {
    val result = parseAll(line, """AB""".stripMargin)
    if(result.successful) println("OK")
    else println("NOT ok")
  }                                           
}

Note:

def line = "A*B" matches only "A*B"

def line = "A*B".r is a regexp for n>=0 repetitions of 'A' followed with 'B'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top