Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract valid email from larger string in Scala

My scala version 2.7.7

Im trying to extract an email adress from a larger string. the string itself follows no format. the code i've got:

import scala.util.matching.Regex
import scala.util.matching._
val Reg = """\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b""".r
"yo my name is joe : [email protected]" match {
    case Reg(e) => println("match: " + e)
    case _ => println("fail")
}

the Regex passes in RegExBuilder but does not pass for scala. Also if there is another way to do this without regex that would be fine also. Thanks!

like image 750
Luigimax Avatar asked Dec 28 '22 16:12

Luigimax


1 Answers

As Alan Moore pointed out, you need to add the (?i) to the beginning of the pattern to make it case-insensitive. Also note that using the Regex directly matches the whole string. If you want to find one within a larger string, you can call findFirstIn() or use one of the similar methods of Regex.

val reg = """(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b""".r
reg findFirstIn "yo my name is joe : [email protected]"  match {
    case Some(email) => println("match: " + email)
    case None => println("fail")
}
like image 140
Mitch Blevins Avatar answered Jan 15 '23 16:01

Mitch Blevins