我的代码可能是如此屠杀,我需要用英语解释一下。基本上我已经创建了一个Date类,我希望它将String作为构造函数并处理两种情况
字符串格式为“2011-06-30” get()返回“2011-06-30 00:00:00.000”
字符串格式为“2011-06-30 16:32:19.452”
get()拆分为rawDate = 2011-06-30和rawTime = 16:32:19.452然后打印
我的尝试在
之下case class Date(date: String) {
// regex
val DateAndTime = """rawDate rawTme""".r
def get(): String = date match {
case DateTime(rawDate, rawTime) => rawDate + "*" + rawTime
case _ => date + " 00:00:00.000"
}
}
不幸的是它甚至没有编译,但我不确定我哪里出错了
答案 0 :(得分:7)
val dateRegex = """([0-9]{4}-[0-9]{2}-[0-9]{2})"""
val timeRegex = """([0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3})"""
val DateOnly = dateRegex.r
val DateTime = (dateRegex + " " + timeRegex).r
def get(s:String) = s match {
case DateTime(d,t) => d + "*" + t
case DateOnly(d) => d + " 00:00:00.000"
}
scala> get("2011-06-30")
res1: java.lang.String = 2011-06-30 00:00:00.000
scala> get("2011-06-30 16:32:19.452")
res2: java.lang.String = 2011-06-30*16:32:19.452