[英]Scala Regex Partial Function with Regex defined in Partial Function
[英]Scala regex and partial functions
我想將Scala的collect函數與正則表達式一起使用。 理想情況下,我只想收集與正則表達式匹配的那些術語。 到目前為止,我已經實現了以下效果很好的方法
val regex = "(^([^:]+):([^:]+):([^:]+):([+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?)$".r
<other_code>.collect{case x: String if regex.pattern.matcher(x).matches =>
x match {
case regex(feature, hash, value, weight) => (feature.split("\\^"), weight.toDouble)
}
}
不過,這似乎還有一個額外的步驟。 我首先檢查正則表達式是否在case語句中匹配以進行收集,然后再檢查它是否再次匹配以提取匹配的組。 有什么方法可以只檢查一次正則表達式匹配嗎?
您不需要第一場比賽:
<other_code>.collect {
case regex(feature, hash, value, weight) => (feature.split("\\^"), weight.toDouble)
}
不需要檢查正則表達式是否匹配,因為模式匹配將為您完成。 讓我用一個稍微簡單的例子來說明。
val regex = "(\\d+),([A-z]+)".r
val input = List("1,a", "23,zZ", "1", "1ab", "")
scala> input collect { case regex(a, b) => (a, b) }
res2: List[(String, String)] = List((1,a), (23,zZ))
使用x match { ... }
可能會導致匹配錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.