scala解析器组合中的Java正则表达式

时间:2015-01-13 05:14:33

标签: java regex scala parser-combinators

我的部分输入如下所示。

Name
John Doe
Sons
Name
Son of John 
28
:
Name
Jane Doe
Daughters
Name
Daughter of Jane 
32
...
...

我的解析器看起来像这样

rep("Name" ~> rep("[A-Z ]+[a-z ]+".r)  ~> ("Sons Name" | "Daughters Name") ~> "[0-9]+") 

但看起来正则表达式rep("[A-Z ]+[a-z ]+".r)也会带走NameDaughter of JaneSon of John,这会导致以下错误:

failure: `Daughters ' expected but `2' found

想知道有一种简单的方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

我已经重新配置了你的解析器,并使一些正则表达式更加明确。此外,我已将skipWhitespace设置为false,因为它可让您对匹配的片段进行更细粒度的控制。我不知道这是否是解决问题的最惯用方法,但它确实有效。希望它有所帮助。

import scala.util.parsing.combinator._

object Parser extends RegexParsers {

  override val skipWhitespace = false

  val word = """[A-Za-z]+""".r
  val separator = """\s+""".r    
  val colon = """(\s+:\s+)?""".r // optional colon
  val ws = """[^\S\n]+""".r      // all whitespace except newline
  val age = "[0-9]+".r

  val name = (repsep(word, ws) <~ separator) ^^ (_.mkString(" "))
  val nameHeader = "Name" ~ separator
  val childNameHeader = ("Daughters" | "Sons") ~ separator ~ nameHeader

  val person = nameHeader ~> name ~ (childNameHeader ~> name) ~ age <~ colon ^^ (p => (p._1._1, p._1._2, p._2))
  val persons = rep(person)

}

object Main extends App {

  val input  =
    """Name
      |John Doe
      |Sons
      |Name
      |Son of John
      |28
      |:
      |Name
      |Jane Doe
      |Daughters
      |Name
      |Daughter of Jane
      |32""".stripMargin

  val result = Parser.parse(Parser.persons, input)
  // prints '[13.3] parsed: List((John Doe,Son of John,28), (Jane Doe,Daughter of Jane,32))'
  println(result)
}