Skip to content

Instantly share code, notes, and snippets.

@jaytaylor
Created March 22, 2012 19:47
Show Gist options
  • Save jaytaylor/2162817 to your computer and use it in GitHub Desktop.
Save jaytaylor/2162817 to your computer and use it in GitHub Desktop.
Scala term string parser
/**
* @author Jay Taylor [@jtaylor]
*
* @date 2011-08-29
*
* @description Eventually I'd like to see this (or something even better)
* included in the scala.sh library.
*/
trait Parsify {
val parsifyTermExtractor = """([+-]?"([^"]|\\")+"|-?\S+)""".r
val parsifyTermCleaner = """^[+-]?"?(.*?)"?$""".r
val emptyTuple2OfStrings = (List[String](), List[String]())
/**
* Parses (+|-)?("a b c"|def) term strings into a Tuple of positive and
* negative elements.
*
* @return Tuple(List[String], List[String])
* Note: ._1 = terms to include, ._2 = terms to exclude.
*/
def parseTerms(terms: String): (List[String], List[String]) =
Option(terms) match {
case Some(terms) =>
terms.trim.length match {
case 0 => emptyTuple2OfStrings
case n =>
val tokens = parsifyTermExtractor.findAllIn(terms).matchData map {
_.group(0)
} toList
def extractMatches(pred: String => Boolean): List[String] =
tokens filter { pred(_) } map {
parsifyTermCleaner.findFirstMatchIn(_).get group 1
} filter { _.length > 0 } toList
val must = extractMatches({ _.charAt(0) != '-' })
val mustNot = extractMatches({ _.charAt(0) == '-' })
(must, mustNot)
}
case None => emptyTuple2OfStrings
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment