Thursday 1 January 2015

Regular Expression in Scala


Create a Regex object by invoking the .r method on a String .e.g
A sequence of one or more numeric characters


scala> val numPattern = "[0-9]+".r
scala> val matches = numPattern.findAllIn(address).toArray
match1: Option[String] = Some(123)

A method defined to return an Option[String] will either return a Some(String), or a None.
The normal way to work with an Option is to use one of these approaches:
  • Call getOrElse on the value.
  • Use the Option in a match expression.
  • Use the Option in a foreach loop.

scala> val result = numPattern.findFirstIn(address).getOrElse("no match")

With the getOrElse approach, you attempt to “get” the result, while also specifying a default value that should be used if the method failed.


No comments:

Post a Comment