Removing nested blocks from a string
I think you are trying to do some pattern matching on strings.

So I did this:

def escape(s: String): String = Seq("{", "}", "whatever").foldLeft(s)((x, y) =&gt; x.replaceAllLiterally(y, "\\" + y))

def removeBlocks(text: String, open: String, close: String): String = {
    val startReg = (s"${escape(open)}(.*)$$").r
    val endReg = (s"${escape(close)}(.*)$$").r
    val otherText = "(.)(.*)$".r

    @tailrec
    def removeBlocksAux(text: String, acc: String = "", lvl: Int = 0): String = {
        assume((text.length() &gt; 0 || lvl == 0) &amp;&amp; lvl &gt;= 0)
        (text, lvl) match {
            case (startReg(text), lvl)     =&gt; removeBlocksAux(text, acc, lvl + 1)
            case (endReg(text), lvl)       =&gt; removeBlocksAux(text, acc, lvl - 1)
            case (otherText(c, text), 0)   =&gt; removeBlocksAux(text, acc + c)
            case (otherText(c, text), lvl) =&gt; removeBlocksAux(text, acc, lvl)
            case ("", _)                   =&gt; acc
        }
    }
    removeBlocksAux(text)
}


I tried to find a way to define the regular expressions inside the match group, but I failed at that, it may not be a good idea after all, but I would like to have a more compact and efficient representation for it. The escape function should escape all special cases of operators in Scala regex, that sounds boring, so there may be already a method for that.

I'm also not a big fan of having a function inside a function, but I kept that design decision. Finally, I'd simply use parser combinators for this, but I guess that's not the point.