You could write your own extractor for this:
object NameRegex {
private val name = """(Mr|Mrs|Ms)\. ([A-Z][a-z]+) ([A-Z][a-z]+)""".r
def unapply(x: String) = name.unapplySeq(x).collect {
case(List(title, first, last)) => (title, first, last)
}
}
And then you could do
val NameRegex(tuple) = "Mr. Charles Darwin"
Person.tupled(tuple)
Or:
"Mr. Ben Reich" match {
case NameRegex(tuple) => Person.tupled(tuple)
}
Or you could make the NameRegex
object match to the Person
object:
object NameRegex {
private val name = """(Mr|Mrs|Ms)\. ([A-Z][a-z]+) ([A-Z][a-z]+)""".r
def unapply(x: String) = name.unapplySeq(x).collect {
case(List(title, first, last)) => Person(title, first, last)
}
}
So then you can extract the person case class in one step:
val NameRegex(p) = "Mr. Barack Obama" //p is Person("Mr", "Barack", "Obama")
val NameRegex(p@Person(title, first, last)) = "Mr. Barack Obama"