Created
June 26, 2010 17:34
-
-
Save ussy/454216 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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