What are Regular Expression Patterns in Scala?

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.

Library

The regex library is required to turn a string into a regular expression.

import scala.util.matching.Regex

Multiple patterns

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.

Code

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.Regex
val number_pattern: Regex = "[0-9]".r
println("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

Copyright ©2025 Educative, Inc. All rights reserved