Blankman Blankman - 2 months ago 20
Scala Question

Pattern matching a domain name

I don't use pattern matching as often as I should.
I am matching a domain name for the following:

1. If it starts with www., then remove that portion and return.
www.stackoverflow.com => "stackoverflow.com"
2. If it has either example.com or example.org, strip that out and return.
blog.example.com => "blog"
3. return request.domain
hello.world.com => "hello.world.com"

def filterDomain(request: RequestHeader): String = {
request.domain match {
case //?? case #1 => ?
case //?? case #2 => ?
case _ => request.domain
}
}


How do I reference the value (request.domain) inside the expression and see if it starts with "www." like:

if request.domain.startsWith("www.") request.domain.substring(4)

Answer

You can give the variable you pattern matching a name and Scala will infer its type, plus you can put an if statement in you case expression as follows

def filterDomain(request: RequestHeader): String = {
request.domain match {
  case domain if domain.startsWith("www.") => domain.drop(4)
  case domain if domain.contains("example.org") | domain.contains("example.com") => domain.takeWhile(_!='.')
  case _ => request.domain
 }
}

Note that the order of the case expressions matters.

Comments