【问题标题】:Scala Parser Combinators: how to define a lineScala Parser Combinators:如何定义一条线
【发布时间】:2015-06-02 00:38:35
【问题描述】:

我正在努力解决以下问题:

class LineParser extends JavaTokenParsers {
   def lines: Parser[Any] = rep(line)
   def line: Parser[String] = """^.+$""".r

}

object LineParserTest extends LineParser {
   def main(args: Array[String]) {
       val reader = new FileReader(args(0))
       println("input : "+ args(0))
       println(parseAll(lines, reader))
   }
}

输入文件:

one
two

当我运行程序时,它给了我这个错误:

[1.1] failure: string matching regex `^.+$' expected but `o' found

one

^

显然,我做了一些愚蠢的事情,但不知道为什么。请指教。

以上是真实目标的简化版本:解析包含命令和子命令的类 cisco 配置文件并构建 AST。有几个命令我不关心,我想使用上面的模式 """^.+$""" 来忽略它们。

【问题讨论】:

    标签: scala parsing


    【解决方案1】:

    您不需要在正则表达式中使用^$。默认情况下. 不匹配行尾,因此以下将使其工作:

    def line: Parser[String] = """.+""".r
    

    在 Java 中,如果您希望 ^$ 匹配行终止符,您必须设置 Pattern.MULTILINE 标志。所以下面的定义也可以:

    def line: Parser[String] = """(?m)^.+$""".r
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      相关资源
      最近更新 更多