david hol
david hol

Reputation: 1280

Scala regex: get value from giver string

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

Upvotes: 1

Views: 121

Answers (2)

airudah
airudah

Reputation: 1179

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

Upvotes: 1

mirosval
mirosval

Reputation: 6822

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

Upvotes: 0

Related Questions