Regular expression patterns in Scala are user-determined strings that we can use for pattern-matching in a text. A string is converted into a regular expression, or regex
, by appending .r
to the string.
The regex
library is required to turn a string into a regular expression.
import scala.util.matching.Regex
This method can also match a group of patterns by using parentheses.
For example, if the regex
is numbers from 0-9
and letters from a-z
, the grouped regular expression would be:
val group_of_patterns = ""([0-9])[ -]([a-z])""
We use [ -]
as a separator, while the numbers and letters are enclosed by square, then normal parentheses.
The following code shows the implementation of regular expression patterns for pattern-matching. The findFirstMatchIn
function is accessible via the regex
library. This function determines whether there is at least one occurrence of the regular expression in the text.
import scala.util.matching.Regexval number_pattern: Regex = "[0-9]".rprintln("Checking first string: ")number_pattern.findFirstMatchIn("The lazy fox jumped over the fence.") match {case Some(_) => println("contains number")case None => println("does not contain number")}println("\nChecking second string: ")number_pattern.findFirstMatchIn("The lazy fox jumped over 1 fence.") match {case Some(_) => println("contains number")case None => println("does not contain number")}
Free Resources