How can I use a regular expression and matching to replace contents of a string? In particular I want to detect integer numbers and increment them. Like so:
val y = "There is number 2 here"
val p = "\\d+".r
def inc(x: String, c: Int): String = ???
assert(inc(y, 1) == "There is number 3 here")
Using replaceAllIn with a replacement function is one convenient way to write this:
val y = "There is number 2 here"
val p = "-?\\d+".r
import scala.util.matching.Regex.Match
def replacer(c: Int): Match => String = {
case Match(i) => (i.toInt + c).toString
}
def inc(x: String, c: Int): String = p.replaceAllIn(x, replacer(c))
And then:
scala> inc(y, 1)
res0: String = There is number 3 here
Scala's Regex provides a handful of useful tools like this, including a replaceSomeIn that takes a partial function, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With