Detecting and converting numbers in a string using regular expressions

How can I use regex and match to replace the contents of a string? Specifically, I want to define integers and increment them. For example:

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")

      

+3


source to share


1 answer


Using replaceAllIn

with the replace function is one of the convenient recording methods:

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 Regex

provides several useful tools such as, including replaceSomeIn

which does a partial function, etc.

+3


source







All Articles