1
所以我有這樣的string
:Scala的正則表達式:從送禮者字符串獲得價值
val str = "\n Displaying names 1 - 20 of 273 in total"
,我想返回Int
名稱的總數,在我的例子:273
所以我有這樣的string
:Scala的正則表達式:從送禮者字符串獲得價值
val str = "\n Displaying names 1 - 20 of 273 in total"
,我想返回Int
名稱的總數,在我的例子:273
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和3之間)
這取決於對句子的整體結構,但應該做的伎倆:
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)
}