如何使用scala解析器解析路径中的错误?

时间:2015-06-13 17:53:12

标签: scala parsing path

我正在编写一个scala解析器来解析以下输入(x是数字): /hdfs://xxx.xx.xx.x:xxxx/path1/file1.jpg+1

  trait pathIdentifier extends RegexParsers{
     def pathIdent: Parser[String] ="""^/hdfs://([\d\.]+):(\d+)/([\w/]+/(\w+\.\w+)$)""".r 
  }


class ParseExp extends JavaTokenParsers with pathIdentifier {
def expr: Parser[Any] = term~rep("+"~term | "-"~term)
def term: Parser[Any] = factor~rep("*"~factor | "/"~factor)
def factor: Parser[Any] = pathIdent | floatingPointNumber | "("~expr~")"
}

我收到以下错误:

  [1.1] failure: `(' expected but `/' found

无法解决问题!

1 个答案:

答案 0 :(得分:2)

这里有两个问题。首先,您尝试匹配以/hfds开头的字符串,但您的输入以/hdfs开头。其次,您拥有的正则表达式将尝试将所有输入与您放置的锚点(^$)匹配。这意味着当使用解析器pathIdent时,它将尝试匹配所有输入,直到Reader没有更多值返回。

在您的输入中,+1之后.jpg\w +不匹配,这就是您解析失败的原因。所以你应该删除它们。

使用expr解析器运行表达式,我得到:

[1.43] parsed: ((/hdfs://111.22.33.4:5555/path1/file1.jpg~List())~List((+~(1~List()))))

这确实是一个因素,其后是空的重复因子(/hdfs://111.22.33.4:5555/path1/file1.jpg~List())),然后重复一个带有+的术语,这是一个因子(1)后跟一个因子空重复的因素(List((+~(1~List()))))。