Scala String matches() Method with Example

Here, we will learn about the matches() method of String class in Scala. It is used to match the string with a regular expression. We will see its working, syntax and example.
Submitted by Shivang Yadav, on February 03, 2021

String is an immutable collection that stores sequences of characters.

String matches() Method

The matches() method on strings is used to check whether the regular expression passed as parameter is present in the string or not.

Syntax:

string_Name.matches(String regex)

Parameters: The method accepts a single parameter which is a regular expression to be check for in the string.

Return Value: It returns a Boolean value based on the presence of the regular expression in string.

Example 1:

object myObject {
    def main(args: Array[String]) {
        val string1 = "includehelp"
        val ismatched = string1.matches(".*help")
    
        if(ismatched){
            println("The string contains the regular expression...")
        }
        else{
            println("The string does not contains the regular expression...")
        }
    }
}

Output:

The string contains the regular expression...

Example 2:

object myObject {
    def main(args: Array[String]) {
        val string1 = "includehelp"
        val ismatched = string1.matches(".*f")
        
        if(ismatched){
            println("The string contains the regular expression...")
        }
        else{
            println("The string does not contain the regular expression...")
        }
    }
}

Output:

The string does not contain the regular expression...



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.