Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are Regular Expression Patterns in Scala?

Sheza Munir

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")
}

RELATED TAGS

scala

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring