Detecting and converting numbers in a string using regular expressions
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 to share