Created
May 13, 2013 10:08
-
-
Save debasishg/5567328 to your computer and use it in GitHub Desktop.
regex interpolation fails ..
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
| Apples-MacBook-Pro:~ debasishg$ scala | |
| Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_45). | |
| Type in expressions to have them evaluated. | |
| Type :help for more information. | |
| scala> :paste | |
| // Entering paste mode (ctrl-D to finish) | |
| implicit class RContext(sc: StringContext) { | |
| def r = | |
| new util.matching.Regex( | |
| sc.parts.mkString(""), | |
| sc.parts.tail.map(_ => "x"): _*) | |
| } | |
| // Exiting paste mode, now interpreting. | |
| defined class RContext | |
| scala> "database:[table1,table2]" matches """(\w+)(:\[(\w+)(,(\w+))*\])?""" | |
| res0: Boolean = true | |
| scala> :paste | |
| // Entering paste mode (ctrl-D to finish) | |
| "database:[table1,table2]" match { | |
| case r"""(\w+)(:\[(\w+)(,(\w+))*\])?""" => true | |
| case _ => false | |
| } | |
| // Exiting paste mode, now interpreting. | |
| res1: Boolean = false | |
| scala> |
Here's also a blog post that gets into some of the details: http://hootenannylas.blogspot.ro/2013/02/pattern-matching-with-string.html
Okay, so your original version works just fine with non-capturing groups. That was the problem.
Author
this works ..
scala> :paste
// Entering paste mode (ctrl-D to finish)
"database:[table1,table2]" match {
case r"""(\w+)$d(:\[(\w+)$f(,(\w+)$x)*$y\])?$t""" => (d, f, x, y, t)
case _ => "no match"
}
// Exiting paste mode, now interpreting.
res29: java.io.Serializable = (database,:[table1,table2],table1,,table2,table2)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your
rmethod should be an extractor object in order to work withmatchexpressions. This is incomplete, but proves the point:Notice however that the pattern in the
matchexpressions uses only non-capturing groups, otherwise it wouldn't match. It's possible to extend the extractor to bind named groups to variables, but I'm not sure it's trivial. This friend of mine has achieved something along these lines here:https://github.com/alexandru/shifter/blob/master/web-api/src/main/scala/shifter/web/api/mvc/PathMatcher.scala
https://github.com/alexandru/shifter/blob/master/web-api/src/test/scala/shifter/web/api/mvc/PathMatcherSuite.scala