Home » Scala programs » Scala string programs

How to determine if a string contains a regular expression in Scala?

Here, we are going to learn how to check if a string contains a regular expression in Scala programming language?
Submitted by Shivang Yadav, on April 14, 2020

In Scala, data validation and adding constraints to its usage is important for data processing. And checking if a regular expression is present in a string.

To check whether the strings contain a regular expression or regex we will use the findFirstIn() method.

Syntax:

    regex.findfirstIn(string)

The method accepts the string in which regex is searched and returns an Option[String] value.

Program to check if a string contains a regular expression

object myObject {
    
    def main(args: Array[String]) {
        val bike = "harley davidson Iron 883"    
        val numRegex = "[0-9]+".r

        println("String: "+bike)

        val matchPattern = numRegex.findFirstIn(bike)

        print("Pattern found "+matchPattern)
    }
}

Output

String: harley davidson Iron 883
Pattern found Some(883)

Explanation:

In this program, we have a string with is to be checked for regular expression which is created using the .r method. The method findFirstIn() is used to check for the presence of the pattern in the string which returns a none if no match is found and the matched string if a match is found.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.