fork download
  1. import scala.util.parsing.combinator.JavaTokenParsers
  2.  
  3. case class IntDef(name: String, value: Int)
  4. case class IntArrayDef(name: String, value: IndexedSeq[Int])
  5.  
  6. object HogeParser extends JavaTokenParsers {
  7. lazy val parse = types ~> repsep((defIntArray | defInt), ",") <~ ";"
  8.  
  9. lazy val types = "int|string".r
  10.  
  11. lazy val defInt = ident ~ ("=" ~> wholeNumber).? ^^ {
  12. case ident ~ None => println(ident + ":" + 0)
  13. case ident ~ Some(default) => println(ident + ":" + default.toString())
  14. }
  15.  
  16. lazy val defIntArray = ident ~ "[" ~ wholeNumber ~ "]" ~ ("=" ~ "{" ~> repsep(wholeNumber, ",") <~ "}").? ^^ {
  17. case ident ~ _ ~ size ~ _ ~ None => println(ident + IndexedSeq.fill(size.toInt)(0).toString())
  18. case ident ~ _ ~ size ~ _ ~ Some(defaults) => println(ident + ":" + defaults.toString())
  19. //println(ident + defaults.map(_.toInt).toIndexedSeq.toString())
  20. }
  21.  
  22. def apply(str: String) = parseAll(parse, str)
  23. }
  24.  
  25. object Main {
  26.  
  27. def main(args: Array[String]): Unit = {
  28. HogeParser("string hoge, hage[3] = { 1, 2, 3 }, huge = 5;").get
  29. }
  30.  
  31. }
  32.  
Success #stdin #stdout 0.34s 247424KB
stdin
Standard input is empty
stdout
hoge:0
hage:List(1, 2, 3)
huge:5