Scala正则表达式和部分函数 [英] Scala regex and partial functions

查看:61
本文介绍了Scala正则表达式和部分函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Scala的collect函数和正则表达式.理想情况下,我只想收集与正则表达式匹配的那些术语.到目前为止,我已经实现了以下效果很好的

I want to use Scala's collect function with a regular expression. Ideally I'd like to collect only those terms that match the regular expression. I've so far implemented the following which works fine

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语句中匹配以进行收集,然后再检查它是否再次匹配以提取匹配的组.有什么方法可以只检查一次正则表达式匹配吗?

This seems to have an extra step though. I'm first checking if the regex matches in the case statement for collect and then I'm checking if it matches again to extract the groups of the match. Is there a way that I can do this with only checking the regex match once?

推荐答案

您不需要第一个匹配项:

You don't need the first match:

<other_code>.collect {
    case regex(feature, hash, value, weight) => (feature.split("\\^"), weight.toDouble)
}

这篇关于Scala正则表达式和部分函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆