Search Strings Using Regex

This tutorial was inspired by the awesome Scala Cookbook.

Create A String

// Create a string value
val attack_order : String = "Our 382 troops will attack their east flank at dawn. They have 28 troops there."

Create A Regex Pattern

// Create a value that is a regex pattern
val find_numbers = "[0-9]+".r

Find First Match

// Apply the regex to find the first match, output the result, otherwise output "None"
find_numbers.findFirstIn(attack_order).getOrElse("None")
382

Find All Matches

// Apply the regex to find all matches and output to an array
find_numbers.findAllIn(attack_order).toArray
Array(382, 28)