Standard Library Utilities
Regex Find
Find digit groups with a standard regular expression.
regex
The `.r` helper turns a string pattern into a regular expression. The example uses safe lookup methods that return an option or a finite iterator.
Regex Find
RegexFind.scala
Replay: real traced execution (multi-file project)
object Main {
def main(args: Array[String]): Unit = {
val text = "order 123 ready"
val digits = "[0-9]+".r
val first = digits.findFirstIn(text).getOrElse("none")
val count = digits.findAllIn(text).toList.length
println("first=" + first)
println("count=" + count)
}
}
object Main {
def main(args: Array[String]): Unit = {
val text = "no digits here"
val digits = "[0-9]+".r
val first = digits.findFirstIn(text).getOrElse("none")
val count = digits.findAllIn(text).toList.length
println("first=" + first)
println("count=" + count)
}
}
object Main {
def main(args: Array[String]): Unit = {
val text = "id 7 and 8"
val digits = "[0-9]+".r
val first = digits.findFirstIn(text).getOrElse("none")
val count = digits.findAllIn(text).toList.length
println("first=" + first)
println("count=" + count)
}
}
text ← order 123 ready, digits ← [0-9]+, first ← 123, count ← 1
1object Main {2 def main(args: Array[String]): Unit = {3 val text→ order 123 ready = "order 123 ready" //@text="no digits here", "id 7 and 8"4 val digits→ [0-9]+ = "[0-9]+".r5 val first→ 123 = digits[0-9]+.findFirstIn(textorder 123 ready).getOrElse("none")6 val count→ 1 = digits[0-9]+.findAllIn(textorder 123 ready).toList.length78 println("first=" + first123)9 println("count=" + count1)10 }11}outputfirst=123 count=1
text ← no digits here, digits ← [0-9]+, first ← none, count ← 0
1object Main {2 def main(args: Array[String]): Unit = {3 val text→ no digits here = "no digits here"4 val digits→ [0-9]+ = "[0-9]+".r5 val first→ none = digits[0-9]+.findFirstIn(textno digits here).getOrElse("none")6 val count→ 0 = digits[0-9]+.findAllIn(textno digits here).toList.length78 println("first=" + firstnone)9 println("count=" + count0)10 }11}outputfirst=none count=0
text ← id 7 and 8, digits ← [0-9]+, first ← 7, count ← 2
1object Main {2 def main(args: Array[String]): Unit = {3 val text→ id 7 and 8 = "id 7 and 8"4 val digits→ [0-9]+ = "[0-9]+".r5 val first→ 7 = digits[0-9]+.findFirstIn(textid 7 and 8).getOrElse("none")6 val count→ 2 = digits[0-9]+.findAllIn(textid 7 and 8).toList.length78 println("first=" + first7)9 println("count=" + count2)10 }11}outputfirst=7 count=2