Help understand regex documentation

I’m looking at the 2.12 documentation here:
but I don’t understand the syntax of the pattern matching.

What do the parens in case docSpree() mean?

In the examples further up in the documentation, you can see that you can add variables here that will be filled with match groups (using the regex’s unapplySeq method).

But even if you don’t have match groups, the parentheses are required, because without them, Scala would interpret the name docSpree as a pattern variable, shadowing the original regex variable. That way, the first case would always match, containing the string you wanted to match against in that variable.

See the differing results:

// with parens: unapplySeq method of docSpree regex
@ val docView  = date.replaceAllIn(dates, _ match {
    case docSpree() => "Historic doc spree!"
    case _          => "Something else happened"
  })
docView: String = "Important dates in history: Something else happened, Something else happened, Something else happened, Historic doc spree!"

// without parens: free pattern variable, matches always
@ val docView  = date.replaceAllIn(dates, _ match {
    case docSpree => "Historic doc spree!"
    case _          => "Something else happened"
  })
docView: String = "Important dates in history: Historic doc spree!, Historic doc spree!, Historic doc spree!, Historic doc spree!"
1 Like