Scala正则表达式:从给予者字符串中获取价值

时间:2016-05-31 14:58:32

标签: regex scala

所以我有这种string

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

我希望在我的示例中返回名称总数的Int273

2 个答案:

答案 0 :(得分: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

显然,调整\\d{1,3}以满足您的要求,其中匹配的数字长度介于1和3之间

答案 1 :(得分:0)

这取决于句子的整体结构,但应该做到这一点:

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