Created
November 30, 2012 16:40
-
-
Save mather/4176860 to your computer and use it in GitHub Desktop.
Parser Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.parsing.combinator.JavaTokenParsers | |
object ParserSample extends JavaTokenParsers { | |
/* | |
* RegexParserで定義されたメソッド。 | |
* default(=true) だと行末の改行などが無視される。 | |
*/ | |
override def skipWhitespace = false | |
/* | |
* パーサ実行 | |
*/ | |
def main(args: Array[String]) = { | |
val input = """|test: token | |
|key : value1 value2 | |
| nextline value1 | |
|thirdKey : test | |
| | |
|body string""".stripMargin | |
println(input) | |
println(parse(entire, input)) | |
} | |
/* | |
* 全体を表すパーサ | |
*/ | |
def entire: Parser[(List[Header],Body)] = | |
(headers <~ "\n") ~ body ^^ { case a~b => (a,b) } | |
/* | |
* コロンで区切られたヘッダリストにマッチ | |
* 複数行に渡る場合は、2行目以降の先頭にスペースが必要 | |
*/ | |
def headers: Parser[List[Header]] = header.+ | |
def header: Parser[Header] = | |
(ident <~ """ *: *""".r) ~ multiline ^^ { | |
case key~value => Header(key,value) | |
} | |
def multiline: Parser[String] = | |
ident ~ (""" *(\n +)?""".r ~> ident).* <~ "\n" ^^ { | |
case a~b => (a :: b).mkString(" ") | |
} | |
/* | |
* 残りを本文とする | |
*/ | |
def body: Parser[Body] = """.*""".r ^^ ( Body(_) ) | |
/* | |
* データを格納する型 | |
*/ | |
case class Header(key: String, value: String) | |
case class Body(body: String) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment