How to check whether a String fully matches a Regex in Scala?

Posted by mkneissl on Stack Overflow See other posts from Stack Overflow or by mkneissl
Published on 2010-06-11T09:54:40Z Indexed on 2010/06/11 12:03 UTC
Read the original article Hit count: 140

Filed under:
|

Assume I have a Regex pattern I want to match many Strings to.

val Digit = """\d""".r

I just want to check whether a given String fully matches the Regex. What is a good and idiomatic way to do this in Scala?

I know that I can pattern match on Regexes, but this is syntactically not very pleasing in this case, because I have no groups to extract:

scala> "5" match { case Digit() => true case _ => false }
res4: Boolean = true

Or I could fall back to the underlying Java pattern:

scala> Digit.pattern.matcher("5").matches
res6: Boolean = true

which is not elegant, either.

Is there a better solution?

© Stack Overflow or respective owner

Related posts about regex

Related posts about scala