v Replacing Parts Of Strings - Scala

Replacing Parts Of Strings

This tutorial was inspired by the awesome Scala Cookbook.

Create A String

// Create a string value
val text: String = "Lt. Steve Miller will be leading the attack."

Create A Regex Pattern

// Create a regex pattern for a name
val find_steve = "Steve Miller".r

Replace Anything That Matches That Pattern With Something Else

// Replace all instances of the pattern with a different name
find_steve.replaceAllIn(text, "Peter Jackson")
Lt. Peter Jackson will be leading the attack.

Replace First Match

// Replace first instance of the pattern with a different name
find_steve.replaceFirstIn(text, "Peter Jackson")
Lt. Peter Jackson will be leading the attack.