问题描述
我有一年,格式为XXYY-ZZ
。例如,年份2020-21
代表从2020年到2021年的一年。我需要提取XXYY
,YY
和ZZ
作为整数,以便以后在计算中使用。>
使用模式匹配和正则表达式,我可以将所需的值提取为字符串,如下所示:
import scala.util.matching.Regex
val YearFormatRegex: Regex = "(20([1-9][0-9]))-([1-9][0-9])".r
"2020-21" match {
case YearFormatRegex(fullStartYear,start,end) => println(fullStartYear,end)
case _ => println("did not match")
}
// will print (2020,20,21)
但是我需要将这些值设置为Ints。有没有一种方法可以将这些值提取为Ints而不用到处抛出.toInt
?我知道正则表达式专门查找数字,因此,如果可以避免的话,将它们提取为String并将 then 解析为Ints似乎是不必要的步骤。
解决方法
如果您想简单地封装转换,一种方法是创建围绕正则表达式构建自己的提取器对象,例如:
import scala.util.matching.Regex
object Year {
private val regex: Regex = "(20([1-9][0-9]))-([1-9][0-9])".r
def unapply(s: String): Option[(Int,Int,Int)] =
s match {
case regex(prefix,from,to) => Some((prefix.toInt,from.toInt,to.toInt))
case _ => None
}
}
"2020-21" match {
case Year(fullStartYear,start,end) => fullStartYear - start + end
case _ => 0
} // returns 2020 - 20 + 21 = 2021
您可以阅读有关提取器对象here on the Scala official documentation的更多信息。
您可以使用此代码here on Scastie。