簡體   English   中英

在Scala中使用解析器組合器時,如何將任意數量的項目轉換為對象?

[英]How do I convert an arbitrary number of items to objects when using parser combinators in Scala?

我一直在與Scala的組合器和解析器一起玩,並且有一個問題可能太簡單了(如果是的話,很抱歉)。 我已經在這段代碼中寫了出來,以使問題易於理解,而我的問題就在結尾。

import scala.util.parsing.combinator._
// First, I create a case class
case class Human(fname: String, lname: String, age: Int)
// Now, I create a parser object
object SimpleParser extends RegexParsers {
 def fname: Parser[String] = """[A-Za-z]+""".r ^^ {_.toString}
 def lname: Parser[String] = """[A-Za-z]+""".r ^^ {_.toString}
 def age: Parser[Int] = """[1-9][0-9]{0,2}""".r ^^ {_.toInt}
 def person: Parser[Human] = fname ~ lname ~ age ^^ {case f ~ l ~ a => Human(f, l, a)}
// Now, I need to read a list of these, not just one. 
// How do I do this? Here is what I tried, but can't figure out what goes inside 
// the curly braces to the right of ^^
// def group: Parser[List[Human]] = rep(person) ^^ {}
// def group: Parser[List[Human]] = (person)+ ^^ {}
}

// Here is what I did to test things:
val s1 = "Bilbo Baggins 123"
val r = SimpleParser.parseAll(SimpleParser.person, s1)
println("First Name: " + r.get.fname)
println("Last Name: " + r.get.lname)
println("Age: " + r.get.age) 
// So that worked well; I could read these things into an object and examine the object,
// and can do things with the object now.
// But how do I read either of these into, say, a List[Human] or some collection?
val s2 = "Bilbo Baggins 123 Frodo Baggins 40 John Doe 22"
val s3 = "Bilbo Baggins 123; Frodo Baggins 40; John Doe 22"

如果有什么很明顯的我想念的地方,請告訴我。 謝謝!

你很親近 對於以空格分隔的版本, rep是您所需要的:

lazy val people: Parser[List[Human]] = rep(person)

對於帶有分號的版本,可以使用repsep

lazy val peopleWithSemicolons: Parser[List[Human]] = repsep(person, ";")

請注意,在兩種情況下rep*返回所需的結果-無需使用^^映射結果。 對於fnamelname也是這種情況,其中正則表達式將隱式轉換為Parser[String] ,這意味着_.toString映射_.toString不會更改任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM