Skip to content

Instantly share code, notes, and snippets.

@chbaranowski
Created June 3, 2012 23:24
Show Gist options
  • Save chbaranowski/2865398 to your computer and use it in GitHub Desktop.
Save chbaranowski/2865398 to your computer and use it in GitHub Desktop.
Scala RegEx Parser Demo
import scala.util.parsing.combinator.RegexParsers
import scala.collection.immutable.Map
import scala.util.parsing.combinator.PackratParsers
/**
* Simple parser for a key value string like:
* key01 = Value01 key02=value02 key03 =value03 key04= value04
*
* The parser does not support whitespace in key or values.
*/
object KeyValueParser extends RegexParsers {
val emptyMap = Map[String, String]()
def keyValues = rep(keyValue) ^^ {
_.foldLeft(emptyMap)((map , pair) => map ++ Map(pair._1 -> pair._2))
}
def keyValue = key ~ value ^^ {
case key ~ value => (key, value)
}
def key = value ~ eq ^^ {
case key ~ eq => key.toString
}
def value = whitespace ~ word ~ whitespace ^^ {
case _ ~ word ~ _ => word.toString
}
def eq = "=".r
def word = "\\w+".r
def whitespace = "\\s*".r
/**
* Parse a key value text into a Map[String, String].
*/
def parse(input: String) = parseAll(keyValues, input) match {
case Success(result,_) => result
case failure : NoSuccess => throw new Exception(failure.msg)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment