Skip to content

Instantly share code, notes, and snippets.

@ussy
Created June 26, 2010 17:34
Show Gist options
  • Save ussy/454216 to your computer and use it in GitHub Desktop.
Save ussy/454216 to your computer and use it in GitHub Desktop.
import scala.util.matching.Regex
object NamedCapturing {
val namedCapture = """\((\?<(.+?)>)(.+?)\)""".r
def regex(path: String) : Regex = {
val (r, names) = parse((path, Array[String]()))
new Regex(r, names: _*)
}
def parse(params: (String, Array[String])) : (String, Array[String]) = {
val path = params._1
namedCapture.findFirstMatchIn(path) match {
case Some(m) => {
val capture = m.group(1)
val name = m.group(2)
return parse((path.replace(capture, ""), params._2 ++ Array(name)))
}
case _ => return params
}
}
}
val re = NamedCapturing.regex("""(?<top>\d{3})-(?<down>\d{4})""")
re.findAllIn("123-4567").matchData.foreach { m =>
println("%s-%s".format(m.group("top"), m.group("down")))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment