Scala regex: get value from receiver string

So, I have this type of string :

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

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

+1
source share
2 answers
 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} according to your requirements when the length of the matching numbers is between 1 and 3 and includes

+1
source

It depends on the overall structure of the proposal, 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) } 
0
source

All Articles