This is an example that puzzled me a few hours …
import scala.util.matching.Regex
val Parse = """class""".r
@annotation.tailrec
def recursion1(s: String): String = {
if (Parse.findAllMatchIn(s).hasNext) recursion1(s.replaceFirst("class", "clazz"))
else s
}
recursion1("This class is a demo and it extends class y.")
@annotation.tailrec
def recursion2(s: String)(pattern: Regex): String = s match {
case pattern(_) => recursion2(s.replaceFirst("class", "clazz"))(pattern)
case _ => s
}
recursion2("This class is basic and extends from a base class")("(class)+".r.unanchored)
I did two versions. The first one uses an iterator with findAllMatchesIn
but I wanted a version which uses pattern matching.
What I was stumbling arround was the missing unanchored
function for the Regex.
So this post should remind me to use unanchored to match for all occurences of the pattern.