Wednesday, January 5, 2011

Groovy to Scala: Regular Expressions

Coming to Scala from Groovy/Java. Scala seems to have a bit more overhead in learning basic concepts so I'm planing on keeping my notes here in a series of short posts. This is not meant by any means to be comprehensive but just a "hello world" for each topic that I wish I had.

Regular Expressions:

Defining: Just add a ".r" after a normal string:

val regEx = "apple*".r

Using: Use in a typical Scala match statement:

val name = ....
name match {
  case regEx => // do your processing here
  case entry => // like default, possibly throw an error
}

Grouping:

val zipMatch = "(\\d+)-(\\d+)"
val zip = "12345-1234"
zip match {
  case regEx(num1, num2) => // num1 == 12345, num2 == 1234
  case entry => // do nothing
}

No comments: