Example #16: Regular Expression Regular expression (aka regex) to identify numbers in a string. Invoking “findFirstIn” and “findAll” functions of the “Regex” class. “[0-9]+”.r is a short form instead of instantiating it as new Regex(“[0-9]+”).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import scala.util.matching.Regex object RegexTest extends App { val numberPattern: Regex = "[0-9]+".r // .r is same as new Regex("[0-9]+") val address = "Suite 121, 79 Belmont Cresent" val result = numberPattern.findFirstIn(address) println(result) //Some(121) println(result.getOrElse("")) //121 val result2 = numberPattern.findAllIn(address) //result2 is Regex.MatchIterator result2.foreach { x => println(s"found a number = $x") } } |
Output
1 2 3 4 5 6 | Some(121) 121 found a number = 121 found a number = 79 |
Example #17:…