Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect and transform numbers in a string using regular expressions

Tags:

regex

scala

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")
like image 576
0__ Avatar asked Nov 25 '25 15:11

0__


1 Answers

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.

like image 190
Travis Brown Avatar answered Nov 27 '25 13:11

Travis Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!