我试图让我的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
}
}
Run Code Online (Sandbox Code Playgroud)
使用:
scala> doesMatchRegEx("foo",".*(foo).*".r)
res36: Boolean = true
scala> doesMatchRegEx("bar",".*(foo).*".r)
res37: Boolean = false
Run Code Online (Sandbox Code Playgroud)
def doesMatchRegEx(subj:String, patt:scala.util.matching.Regex) = subj match {
case patt(_) => true
case _ => false
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,这实际上使'doMatchRegEx方法变得多余.
就像这样:
"foo".matches(".*(foo).*") // => true
"bar".matches(".*(foo).*") // => false
".*(foo).*".r.findFirstIn("foo").isDefined // => true
Run Code Online (Sandbox Code Playgroud)