1

我试图解析两个 Ints 和一些元素的输入和结尾:

import scala.util.parsing.combinator.JavaTokenParsers

class X extends JavaTokenParsers {
  lazy val elems = elem("wrong elem", "#WB-" contains _)
  lazy val lists = repsep(rep(elems), ",")
  lazy val p1 = int ~ int ~ lists
  lazy val p2 = int ~ int ~ (whiteSpace ~> lists)

  def go[A](p: Parser[A]) = parseAll(p, "1 2   WB#,---,BBB") match {
    case NoSuccess(msg, _) => sys.error(msg)
    case _ =>
  }

  lazy val int: Parser[Int] =
    wholeNumber ^^ {
      try _.toInt catch {
        case e: NumberFormatException => sys.error("invalid number")
      }
    }
}

方法中给出了一个示例输入go。Ints 和末尾的元素必须用空格分隔。但这仅适用于 Ints 而不适用于元素。当我输入

val x = new X
x go x.p1

我收到以下错误:

java.lang.RuntimeException: string matching regex `\z' expected but `W' found

但是当我输入

x go x.p1

我得到:

java.lang.RuntimeException: string matching regex `\s+' expected but `W' found

最后我想要一个Parser[Int ~ Int ~ List[List[Char]]]. 为什么在前面插入空格elem不起作用?我怎样才能让这个代码工作?

4

1 回答 1

2

只需用 RegEx Parser 替换 elems :

import scala.util.parsing.combinator.JavaTokenParsers

class X extends JavaTokenParsers {

lazy val elems = "[#WB-]".r
lazy val lists = repsep(rep(elems), ",")
lazy val p1 = int ~ int ~ lists

def go[A](p: Parser[A]) = parseAll(p, "1 2   WB#,---,BBB") match {
case NoSuccess(msg, _) => sys.error(msg)
case _ =>
}

lazy val int: Parser[Int] =
wholeNumber ^^ {
try _.toInt catch {
    case e: NumberFormatException => sys.error("invalid number")
  }
}
}

我删除了 p2 因为现在没用了

于 2012-03-23T10:18:58.183 回答