Matching against a regular expression in Scala

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("[email protected]")
res1: Option[String] = Some([email protected])

scala> Email.findFirstIn("test")
rest2: Option[String] = None

You could even extract :

scala> val Email(name, domain) = "[email protected]"
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> "[email protected]".matches(Email.toString)
res6: Boolean = true

Hope this will help.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)