Regex Scala正则表达式:从给定器字符串获取值

Regex Scala正则表达式:从给定器字符串获取值,regex,scala,Regex,Scala,所以我有这样的字符串: val str = "\n Displaying names 1 - 20 of 273 in total" 我想返回姓名总数的Int,在我的示例中:273这取决于句子的整体结构,但应该做到: val str = "\n Displaying names 1 - 20 of 273 in total" val matches = """of\s+(\d+)\s+in total""".r.findAllMatchIn(str) matches.foreach {

所以我有这样的
字符串

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

我想返回姓名总数的
Int
,在我的示例中:
273
这取决于句子的整体结构,但应该做到:

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)
}
显然,如果要匹配的数字长度介于1和3之间,请调整
\\d{1,3}
,以满足您的要求

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