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

One Reply to “Scala regex anchored example”

  1. Your first example is probably wrong, because by default pattern-matching using a regex constructed like `”””^(\d\d\d\d)$”””.r` matches the entire input. So your first snippet would actually NOT result in a match:

    “`
    scala> val date = “””(\d\d\d\d)”””.r
    date: scala.util.matching.Regex = (\d\d\d\d)

    scala> val copyright: String = “Year: 2016″ match {
    | case date(year) => s”Copyright $year”
    | case _ => “No match”
    | }
    copyright: String = No match
    “`

    To check if the pattern matches anywhere in the input, you would need an unanchored regex using the `unanchored` method: `”””(\d\d\d\d)”””.r.unanchored`. The below snippet produces a match:

    “`
    scala> val dateUnanchored = “””(\d\d\d\d)”””.r.unanchored
    dateUnanchored: scala.util.matching.UnanchoredRegex = (\d\d\d\d)

    scala> val copyright: String = “Year: 2016″ match {
    | case dateUnanchored(year) => s”Copyright $year”
    | case _ => “No match”
    | }
    copyright: String = Copyright 2016
    “`

Leave a Reply

Your email address will not be published.