Skip to content

Instantly share code, notes, and snippets.

@voronaam
Last active December 27, 2015 02:58
Show Gist options
  • Save voronaam/7255573 to your computer and use it in GitHub Desktop.
Save voronaam/7255573 to your computer and use it in GitHub Desktop.
A function to parse page set definitions with ranges. No negative numbers (it is for page numbers).
// A function to parse page set defintion, which supports [overlapping] ranges
def pageSet(definition: String) = {
def pageDefToSet(pageDef: String): Set[Int] = {
val rangeExtractor = """[^\d]*([\d]+).*-[^\d]*([\d])+[^\d]*""".r
val numberExtractor = """[^\d]*([\d]+)[^\d]*""".r
pageDef match {
case rangeExtractor(from, to) => (from.toInt to to.toInt).toSet
case numberExtractor(num) => Set(num.toInt)
case _ => Set()
}
}
definition.split(",").foldLeft(Set[Int]())((x, part) => x ++ pageDefToSet(part))
}
pageSet("1,2,3,6-8,sdf,12").toList.sorted //> res0: List[Int] = List(1, 2, 3, 6, 7, 8, 12)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment