v Extract Substrings Using Regex - Scala

Extract Substrings Using Regex

This tutorial was inspired by the awesome Scala Cookbook.

Create String

// Create a string value
val text: String = "27 aircraft"

Create Regex Pattern

// Create a regex with two pattern matches (one number and one word)
val pattern = "([0-9]+) ([A-Za-z]+)".r

Extract Substrings That Match Regex

// Apply the regex pattern such that each of the two pattern matches is assigned to a seperate value
val pattern(vehicle_number, vehicle_type) = text

View Output

// View the value
vehicle_number
27
// View the value
vehicle_type
aircraft