Scala regex anchored example

The “anchored” function on a Scala regular expression forces the regular expression to match the entire string (i.e. anchored to the beginning and end of the string).

For example, consider an unanchored regular expression, which matches any part of a string:

val date = """(\d\d\d\d)""".r

val copyright: String = "Year: 2016" match {
  case date(year) => s"Copyright $year"
  case _ => "No match"
}
copyright: String = Copyright 2016

We can force this to match the whole string (which will fail for our example string):

val date = """(\d\d\d\d)""".r.anchored

val copyright: String = "Year: 2016" match {
  case date(year) => s"Copyright $year"
  case _ => "No match"
}
copyright: String = No match

This is essentially equivalent to adding ^ and $ inside the regular expression, to forece matching the string to the beginning and end:

val date = """^(\d\d\d\d)$""".r

When you call “anchored” you can reverse the effect with the “unanchored” function:

val date = """(\d\d\d\d)""".r.anchored

val copyright: String = "Year: 2016" match {
  case date.unanchored(year) => s"Copyright $year"
  case _ => "No match"
}
copyright: String = Copyright 2016

However, “unanchored” and “anchored” just set an internal flag – they don’t consider the regular expression itself, so they will not remove the effects of ^ and $ in the regular expression:

val date = """^(\d\d\d\d)$""".r

val copyright: String = "Year: 2016" match {
  case date.unanchored(year) => s"Copyright $year"
  case _ => "No match"
}
copyright: String = No match