Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: split string via pattern matching

Is it possible to split string into lexems somehow like

"[email protected]" match {
    case name :: "@" :: domain :: "." :: zone => doSmth(name, domain, zone)
}

In other words, on the same manner as lists...

like image 795
tmporaries Avatar asked Jan 16 '14 19:01

tmporaries


1 Answers

Yes, you can do this with Scala's Regex functionality.

I found an email regex on this site, feel free to use another one if this doesn't suit you:

[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}

The first thing we have to do is add parentheses around groups:

([-0-9a-zA-Z.+_]+)@([-0-9a-zA-Z.+_]+)\.([a-zA-Z]{2,4})

With this we have three groups: the part before the @, between @ and ., and finally the TLD.

Now we can create a Scala regex from it and then use Scala's pattern matching unapply to get the groups from the Regex bound to variables:

val Email = """([-0-9a-zA-Z.+_]+)@([-0-9a-zA-Z.+_]+)\.([a-zA-Z]{2,4})""".r
Email: scala.util.matching.Regex = ([-0-9a-zA-Z.+_]+)@([-0-9a-zA-Z.+_]+)\.([a-zA-Z]    {2,4})


"[email protected]" match {
    case Email(name, domain, zone) =>
       println(name)
       println(domain)
       println(zone)
}

// user
// domain
// com
like image 111
Akos Krivachy Avatar answered Oct 01 '22 01:10

Akos Krivachy