tags:

views:

209

answers:

1
+2  Q: 

Idiomatic 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
+8  A: 
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
Kris Nuttycombe
In my eager to use Scala, I completely forgot that I'm using java.lang.String and that it has a matches-method. Thanks for that :-) About the match-case-thing - also nice, but as I see it, I still have to wrap it in a method to use it as a boolean expression - how is it superfluous?
Grav
Since everything in Scala gives back something the match also does this. So you can write val b = subj match ... and b will contain true/false. If thats what you mean?
Plankalkül
Yes you're right, the match could just be used instead. I didn't get that at first.
Grav