Last active
April 27, 2018 13:44
-
-
Save davidallsopp/6747395 to your computer and use it in GitHub Desktop.
Scala regex and pattern matching example - phone numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.matching.Regex | |
object regex { | |
val number = "07923 874123" //> number : String = 07923 874123 | |
val pattern = """(\d{5})[ -]?(\d{6})""" //> pattern : String = (\d{5})[ -]?(\d{6}) | |
number.matches(pattern) //> res0: Boolean = true | |
// Compiled pattern | |
val Phone = pattern.r //> Phone : scala.util.matching.Regex = (\d{5})[ -]?(\d{6}) | |
// Integrates with Scala pattern matching: | |
number match { case Phone(area, num) => num } //> res1: String = 874123 | |
// and Options: | |
Phone findFirstIn number //> res2: Option[String] = Some(07923 874123) | |
// Multiple matches: | |
val numbers = "07923 874123, 07923-874124, 07923874125" | |
//> numbers : String = 07923 874123, 07923-874124, 07923874125 | |
(Phone findAllIn numbers) foreach println //> 07923 874123 | |
//| 07923-874124 | |
//| 07923874125 | |
(Phone findAllMatchIn numbers) map (_ group 2) foreach println | |
//> 874123 | |
//| 874124 | |
//| 874125 | |
// Avoids 'magic' group numbers, but matches twice: | |
(Phone findAllIn numbers) foreach {case Phone(a,n) => println(n)} | |
//> 874123 | |
//| 874124 | |
//| 874125 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment