I have been playing with Scala's combinators and parsers, and have a question that may be too elementary (apologies if it is). I have written it out in this code to make the question easy to understand and my question is at the end.
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"
If there is something very obvious I missed please let me know. Thanks!
You were very close. For the space-separated version, rep
is all you need:
lazy val people: Parser[List[Human]] = rep(person)
And for the version with semicolons, you can use repsep
:
lazy val peopleWithSemicolons: Parser[List[Human]] = repsep(person, ";")
Note that in both cases rep*
returns the result you want—there's no need to map over the result with ^^
. This is also the case for fname
and lname
, where the regular expression will be implicitly converted into a Parser[String]
, which means that mapping _.toString
doesn't actually change anything.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.