Grav
Grav

Reputation: 1714

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

Upvotes: 2

Views: 1060

Answers (1)

Kris Nuttycombe
Kris Nuttycombe

Reputation: 4580

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

Upvotes: 9

Related Questions