Search code examples
scalaregexp-replace

How to access the replaceAllIn() counter?


I am using

val str2 = regex.replaceAllIn(str1, "other")

and need to count the number of replaces... There are a way retrieve the value of the internal replaceAllIn counter?

PS: this is usual in other languages (example), so I am supposing that Scala offer similar thing.


Solution

  • scala> val r = "x".r
    r: scala.util.matching.Regex = x
    
    scala> var i = 0
    i: Int = 0
    
    scala> r.replaceAllIn("xooxxox", m => { i += 1 ; "X" })
    res0: String = XooXXoX
    
    scala> i
    res1: Int = 4
    

    will do appendReplacement under the hood.