[英]Idiomatic regex matching in Scala
我试图让我的Scala代码更加惯用。 现在它看起来像Java代码。
我正在尝试在Scala中做一个简单的布尔正则表达式匹配函数,因为我似乎无法在标准库中找到它(?)
我不认为try-catch和所有的结果都特别好。 另外,前提条件是'patt'只有一个组,我实际上并没有用它。 有什么输入?
def doesMatchRegEx(subj:String, patt:scala.util.matching.Regex) = {
try{
val Match = patt
val Match(x) = subj
true
} catch {
// we didnt match and therefore got an error
case e:MatchError => false
}
}
采用:
scala> doesMatchRegEx("foo",".*(foo).*".r)
res36: Boolean = true
scala> doesMatchRegEx("bar",".*(foo).*".r)
res37: Boolean = false
def doesMatchRegEx(subj:String, patt:scala.util.matching.Regex) = subj match {
case patt(_) => true
case _ => false
}
正如您所看到的,这实际上使'doMatchRegEx方法变得多余。
就像这样:
"foo".matches(".*(foo).*") // => true
"bar".matches(".*(foo).*") // => false
".*(foo).*".r.findFirstIn("foo").isDefined // => true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.