I personally dislike Scala's Regex. However, I haven't ever been able to come up with something truly superior -- aside from one or two minor suggestions that have been incorporated in the library.
So, I'll present two ways to do this using Scala's regex, but, first, I'll like to just mention that Scala's String is Java's String, so any method present in Java is present in Scala, as far as strings are concerned. So, if your use case is easily solved by chaining ".replace", then, by all means, go for it.
So, if one wants to explore Scala options to handle this, the first way is to convert the regex into a replacing function:
val f1 = "a".r replaceAllIn (_: String, "1")
val f2 = "b".r replaceAllIn (_: String, "2")
val f3 = f1 andThen f2
f3("aabbabab")
The second way is to take advantage of Scala's ability to accept closures for replacement:
import scala.util.matching.Regex.Match
def f = "[ab]".r replaceSomeIn ( _: String, {
case Match("a") => Some("1")
case Match("b") => Some("2")
case _ => None } )
f("aabbXabab")
This later example works better if things are really dynamic. You could, then do stuff like this:
type Matcher = PartialFunction[Match, String]
implicit def toMakeMatcher(pattern: String) = new { def makeMatcher(pf: Matcher) = (pattern, pf) }
def replacer(replacements: (String, Matcher)*) = {
val (patterns, matchers) = replacements.unzip
(patterns mkString "|").r replaceSomeIn (_: String, matchers reduceLeft (_ orElse _) lift)
}
val f1 = "a" makeMatcher { case Match("a") => "1" }
val f2 = "b" makeMatcher { case Match("b") => "2" }
val f3 = replacer(f1, f2)
f3("aabbXabab")
Or even,
implicit def toReplacer(pattern: String) = new { def replaceWith(replacement: String): (String, Matcher) = { val regex = pattern.r; (pattern, { case regex() => replacement }) } }
val f4 = "a" replaceWith "1"
val f5 = "b" replaceWith "2"
val f6 = replacer(f4, f5)
f6("aabbXabab")
So, there's your thought snack for today. :-)
--
Daniel C. Sobral
I travel to the future all the time.