I fairly frequently match strings against regular expressions. In Java:
java.util.regex.Pattern.compile(\"\\w+\").matcher(\"this_is\").matches
Ouch. Scala has
You can define a pattern like this :
scala> val Email = """(\w+)@([\w\.]+)""".r
findFirstIn
will return Some[String]
if it matches or else None
.
scala> Email.findFirstIn("test@example.com")
res1: Option[String] = Some(test@example.com)
scala> Email.findFirstIn("test")
rest2: Option[String] = None
You could even extract :
scala> val Email(name, domain) = "test@example.com"
name: String = test
domain: String = example.com
Finally, you can also use conventional String.matches
method (and even recycle the previously defined Email Regexp
:
scala> "david@example.com".matches(Email.toString)
res6: Boolean = true
Hope this will help.