开发者

Idiomatic regex matching in Scala

I'm trying to get my Scala code to be a bit more idiomatic. Right now it just looks like Java code.

I'm trying to do a simple boolean regex matching function in Scala, since I cannot seem to find it in the standard library(?)

I don't think the resul开发者_Python百科t is particularly nice with the try-catch and all. Also, a precondition is that 'patt' has exactly one group, which I don't really use for anything. Any input?

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
    }
}

Use:

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
}

As you can see, this actually makes the 'doesMatchRegEx method kind of superfluous.

As does this:

"foo".matches(".*(foo).*") // => true
"bar".matches(".*(foo).*") // => false
".*(foo).*".r.findFirstIn("foo").isDefined // => true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜