Scala Language Regular Expressions Declaring regular expressions


Example

The r method implicitly provided via scala.collection.immutable.StringOps produces an instance of scala.util.matching.Regex from the subject string. Scala's triple-quoted string syntax is useful here, as you do not have to escape backslashes as you would in Java:

val r0: Regex = """(\d{4})-(\d${2})-(\d{2})""".r     // :)
val r1: Regex = "(\\d{4})-(\\d{2})-(\\d{2})".r // :(

scala.util.matching.Regex implements an idiomatic regular expression API for Scala as a wrapper over java.util.regex.Pattern, and the supported syntax is the same. That being said, Scala's support for multi-line string literals makes the x flag substantially more useful, enabling comments and ignoring pattern whitespace:

val dateRegex = """(?x:
   (\d{4}) # year
  -(\d{2}) # month
  -(\d{2}) # day
)""".r

There is an overloaded version of r, def r(names: String*): Regex which allows you to assign group names to your pattern captures. This is somewhat brittle as the names are disassociated from the captures, and should only be used if the regular expression will be used in multiple locations:

"""(\d{4})-(\d{2})-(\d{2})""".r("y", "m", "d").findFirstMatchIn(str) match {
  case Some(matched) =>
    val y = matched.group("y").toInt
    val m = matched.group("m").toInt
    val d = matched.group("d").toInt
    java.time.LocalDate.of(y, m, d)
  case None => ???
}