title: Replace nth occurrence to its reverse
body: <p>Scala provides out of the box methods to work either with first or with all occurrences of the pattern.</p>
  
  <p><strong>What is the best (or canonical way) to replace only nth occurrence?</strong></p>
  
  <p>I can think of a couple of solutions but I do not really like any of them.</p>
  
  <p>First one uses mutable var to track occurrences.</p>
  
  <pre><code>  def f1(str: String, pattern: String, occurrence: Int) = {
      pattern.r.replaceAllIn(str, {var c = 0
        m: Match =&gt; {
        c = c + 1
        if (c == occurrence) m.group(1).reverse else m.group(1)
        }
      })
    }
  
    println(f1("aaa bbb123, ccc456, ddd789, qqq1010 206z", """(\d+)""", 3))
  </code></pre>
  
  <p>Second one finds all matches, picks up the required and applies patch method for the String.</p>
  
  <pre><code>  def f2(str: String, pattern: String, occurrence: Int) = {
      val m = pattern.r.findAllMatchIn(str).toList.lift(occurrence-1)
      m match {
        case Some(m) =&gt; str.patch(m.start(1), m.group(1).reverse, m.group(1).length)
        case None =&gt; str
      }
    }
  
    println(f2("aaa bbb123, ccc456, ddd789, qqq1010 206z", """(\d+)""", 3))
  </code></pre>
  
  <p>Is there more concise/preferable or better way?</p>
  
  <p><strong>Update</strong></p>
  
  <p>Yet another approach with zipAll.</p>
  
  <pre><code>  def f5(str: String, pattern: String, occurrence: Int) = {
      val m = pattern.r.findAllIn(str).toArray
      val x = str.split(pattern)
      if (x.size&gt;occurrence) m(occurrence-1) = m(occurrence-1).reverse
      x.zipAll(m, "", "").flatMap(t =&gt; List(t._1, t._2)).mkString
    }
  </code></pre>
  
  <p>Results of the performance test for functions f1...f5 with 1 000 000 executions and below function to measure elapsed time</p>
  
  <pre><code>  def time[R](block: =&gt; R): R = {
      val t0 = System.nanoTime()
      val result = block    // call-by-name
      val t1 = System.nanoTime()
      println("Elapsed time: " + (t1 - t0) + "ns")
      result
    }
  
  Elapsed time: 6352446800ns
  Elapsed time: 4832129400ns
  Elapsed time: 3153650800ns
  Elapsed time: 3501623300ns
  Elapsed time: 6276521500ns
  </code></pre>
  
  <p>f3 seems to be the best (which is expected).</p>