1

So i have this kind of string:

val str = "\n  Displaying names 1 - 20 of 273 in total"

And i want to return Int of the total number of names, in my example: 273

david hol
  • 1,272
  • 7
  • 22
  • 44

2 Answers2

1
scala> import scala.util.matching.Regex
import scala.util.matching.Regex

scala> val matcher = new Regex("\\d{1,3}")
matcher: scala.util.matching.Regex = \d{1,3}

scala> val string = "\n  Displaying names 1 - 20 of 273 in total"
string: String =
"
  Displaying names 1 - 20 of 273 in total"

scala> matcher.findAllMatchIn(string).toList.reverse.head.toString.toInt
res0: Int = 273

Obviously, adjust \\d{1,3} to suit your requirements where the lenght of numbers to match are between and including 1 and 3

airudah
  • 1,169
  • 12
  • 19
0

This depends on the overall structure of the sentence, but should do the trick:

val str = "\n  Displaying names 1 - 20 of 273 in total"

val matches = """of\s+(\d+)\s+in total""".r.findAllMatchIn(str)

matches.foreach { m =>
  println(m.group(1).toInt)
}
mirosval
  • 6,671
  • 3
  • 32
  • 46