Created
April 27, 2011 00:18
-
-
Save ssuravarapu/943469 to your computer and use it in GitHub Desktop.
Parser combinators using Scala
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
case class AcceptHeader(mediaType: String, mediaSubType: String, qualityFactor: Float) |
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 util.parsing.combinator._ | |
object AcceptHeaderParser extends JavaTokenParsers { | |
lazy val accept: Parser[List[AcceptHeader]] = rep1sep(acceptEntry, ",") | |
lazy val acceptEntry: Parser[AcceptHeader] = (mediaType <~ "/") ~ mediaSubType ~ opt(qualityFactor) ^^ { | |
case t ~ st ~ Some(q) => AcceptHeader(t, st, q.toFloat) | |
case t ~ st ~ None => AcceptHeader(t, st, 1.0F) | |
} | |
lazy val wordRegex = """[\w+\-*]*""".r | |
lazy val mediaType = wordRegex | |
lazy val mediaSubType = wordRegex | |
lazy val qualityFactor = ";" ~> "q" ~> "=" ~> floatingPointNumber | |
def parse(input: String): List[AcceptHeader] = parseAll(accept, input).getOrElse(Nil) | |
} |
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
object AcceptHeaderTest { | |
def main(args: Array[String]) { | |
println(AcceptHeaderParser.parseAndOrder(""" application/html;q=0.8, text/*, text/xml, application/json;q=0.9 """)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment