2013-01-01 45 views
0

我想基於正則表達式匹配自動將字符串轉換爲日期。我的代碼到目前爲止是如下:斯卡拉地圖[正則表達式,字符串] collectFirst錯誤

package be.folks.date 

import java.util.Date 
import scala.util.matching.Regex 
import org.joda.time.format.DateTimeFormat 

class StringToDate(underlying:String) { 

    val regmap : Map[Regex, String] = Map(
    ("""\d\d-\d\d-\d\d\d\d""".r, "dd-MM-yyyy"), 
    ("""\d\d-\w\w\w-\d\d\d\d""".r, "dd-MMM-yyyy") 
) 

    def toDate() : Date = { 
    DateTimeFormat.forPattern((regmap collectFirst { case (_(underlying) , v) => v } get)).parseDateTime(underlying).toDate() 
    } 

} 

object StringToDate { 
    implicit def +(s:String) = new StringToDate(s) 
} 

不過,我得到一個錯誤「_」 - 但卻發現()

我該如何解決這個

回答

1

我? 。不知道我理解你的語法應用正則表達式也許,在toDate,你想:

regmap collectFirst { 
    case (pattern , v) if((pattern findFirstIn underlying).nonEmpty) => v} 

我也不會用get從選項中提取的字符串,因爲它扔如果找不到匹配的正則表達式,則是一個例外。我不知道如何在代碼中管理這種情況,所以我不能給你提供建議。

+0

我打算把它留在例外:) – 0n4li

相關問題