EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Scala Regex

By Shalu SharmaShalu Sharma

Home » Software Development » Software Development Tutorials » Scala Tutorial » Scala Regex

Scala Regex

Introduction to Scala Regex

This is a guide to Scala Regex. Regex stands for regular expression. We can define some pattern using regular expression and we can use this regular expression to test our input parameter passed. Regular expression is used in so many different programming languages. In scala they work in the same way like Java. We write our regular expression in some pattern or it is a sequence of character to check our string or integer passed is valid or not.

How Regex work in Scala?

In scala regular expression works in the same way like they work in other languages. In scala we can find this class inside scala.util.matchingpackage named Regex. So this is the full path of the package >>scala.util.matching.Regex. We use this Regex class to search substring within a string or for parsing as well. We can follow to approach to deal with regular expression. We can direct assign our regular expression to string then convert it to regex object but calling some method. Also we can do one more thing like we can pass our pattern to regex object only.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

1. Convert string to regex object

To convert our string to regex object we can call r() method of scala to again recast it to regex object.

Syntax:

valstr = "Here is some string".r

In this above code what is happening like we are casting our string to regex object by calling r() method on it.

2. Direct assign to regex object

In this approach we can directly assign our string to regex object only without need of calling the r() method explicitly.

Syntax:

valreg = new Regex("(A|b)fh")

In the above syntax we are passing our pattern directly to regex object only.

Popular Course in this category
Scala Programming Training (3 Courses,1Project)3 Online Courses | 9+ Hours | Verifiable Certificate of Completion | Lifetime Validity | 1 Project
4.5 (5,543 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)All in One Software Development Bundle (600+ Courses, 50+ projects)

Scala Regex Functions

We have so many different functions available in scala regex class to handle our string or input passed.

Given below is the list of various functions with example:

1. findAllIn(source: CharSequence)

This will find the substring into the source string.

Example:

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valstr = "Hello to all".r
val source = "Hello to all from world"
println(strfindFirstIn source)
}

Output:

Scala Regex 1

2. findAllMatchIn(source: CharSequence)

Find all non-overlapping. Print those string as output.

Example:

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valstr = "Hello to all to test regularexpression".r
val source = "Hello to all from world"
println(strfindAllMatchIn source)
}

Output:

Scala Regex 2

3. findFirstIn(source: CharSequence)

This method will find the first occurrence of string from source and print it.

Example:

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here
valstr = "to".r
val source = "Hello to all from world"
println(strfindFirstIn source)
}

Output:

Scala Regex 3

4. replaceAllIn()

It will replace the string with specified input.

Example:

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valstr = "replacetest"
valfinalstr = "replacetest".replaceAll(".test", "**")
println("befor ::" + str)
println("aftre ::" + finalstr)
}

Output:

replaceAllIn()

5. replaceFirst()

replace first occurrence.

Example:

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valstr = "replacetest"
valfinalstr = "replacetest".replaceFirst(".test", "**")
println("befor ::" + str)
println("aftre ::" + finalstr)
}

Output:

replaceFirst()

6. matches()

This method is going to match the string with pattern we pass and it will return true or false based on the result or if it got the string matches with the pattern.

Example:

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
varstr = "check"
valfinalstr = str.matches(".*k")
// Displays output
println(finalstr)
}

Output:

matches()

7. split(String regex, int limit)

It will give us the array in return, but we can limit the number of objects in the array while returning.

Example:

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
varstr = "somestring to test the result"
valfinalstr = str.split(".ng", 4)
for ( s1 <-finalstr )
{
// Displays output
println( "Here the array ::"+s1)
}
}

Output:

scala Regex 7

Examples of Scala Regex

Given below are the examples mentioned:

Example #1

\\d: It matched digit in any input passed [0-9]. This method checks for digit in an input.

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valreg = new Regex("\\d")
valstr = "to check digit 520 in string"
println((regfindAllInstr).mkString(", "))
}

Output:

scala regex 8

Example #2

\\D: This method checks in the input passes whether it contains the non-digit.

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valreg = new Regex("\\D")
valstr = "to check string 520 in string"
println((regfindAllInstr).mkString(", "))
}

Output:

scala regex 9

Example #3

\\S: Check the non-white space.

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valreg = new Regex("\\S")
valstr = "to check string 520 in string"
println((regfindAllInstr).mkString(", "))
}

Output:

scala regex 10

Example #4

\\s: This method basically checks for white space present in the string and print them. [\t\n\r\f]

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valreg = new Regex("\\s")
valstr = "to check string 520 in string"
println((regfindAllInstr).mkString(", "))
}

Output:

checks for white space present in the string

Example #5

q|r: This expression check whether the string contains the q or r not and print them.

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valreg = new Regex("q|r")
valstr = "Check regular expression"
println((regfindAllInstr).mkString(", "))
}

Output:

check whether the string contains the q or r

Example #6

.: This method is used to check the new line. “.” Check in the string or input parameter if contain any new line.

Code:

import scala.util.matching.Regex
object Main extends App{
// Your code here!
valreg = new Regex(".")
valstr = "check for new line "
// printing them out.
println((regfindAllInstr).mkString(", "))
}

Output:

scala regex 13

Conclusion

So Scala Regex is similar to any other regular expression. It is basically used for searching and parsing in our input parameters that we passed for validation purpose. We can create different type of pattern and validate our input against them. Regular expression provides us many unbuild expression as well.

Recommended Articles

This is a guide to Scala Regex. Here we discuss how regex work in scala, scala regex functions with examples for better understanding. You may also have a look at the following articles to learn more –

  1. Scala Abstract Class
  2. Scala High Order Functions
  3. Scala foreach
  4. Scala Versions

Scala Programming Training (3 Courses,1Project)

3 Online Courses

9+ Hours

Verifiable Certificate of Completion

Lifetime Validity

1 Project

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Scala Tutorial
  • Advanced
    • Constructors in Scala
    • Scala Class Constructor
    • Scala Abstract Class
    • Scala String
    • Scala Collections
    • Scala High Order Functions
    • Scala Date Function
    • Scala Stream
    • Scala Class
    • Scala Function
    • Scala Closure
    • Scala Range
    • Scala Either
    • Scala Random
    • Scala Tuples
    • Scala Partial Function
    • Scala Split
    • Scala Finds
    • Scala List
    • Scala Trait
    • Scala Try Catch
    • Scala Regex
    • Scala Vector
    • Scala Seq
    • Scala Byte
    • Scala ListBuffer
    • Scala ArrayBuffer
    • Scala flatMap
    • Scala HashMap
    • Scala Map Function
    • Scala SortBy
    • Scala Some
    • Scala Generic
    • Scala getOrElse
    • Scala REPL
    • Scala Logging
    • Scala Lambda
    • Scala Queue
    • Scala Set
    • Scala Singleton
    • Scala groupBy
    • Scala reduce
    • Scala filter
    • Scala Option
    • Scala Native
    • Scala DataFrame
    • Scala Anonymous Function
    • Scala Read File
    • Scala Write to File
    • Scala Pattern Matching
    • Scala ClassTag
    • Scala Synchronized
    • Scala zipwithindex
    • Scala Interview Questions
  • Basics
    • What is Scala?
    • Uses of Scala
    • Scala Versions
    • Scala Data Types
    • Scala Companion Object
    • Scala Operators
    • Scala: The Functional Approach
    • Scala Object
    • Scala Implicit
    • Scala IDE
  • Control Flow
    • Scala if else
    • Break in Scala
    • Scala for Loop
    • Scala foreach
    • Scala While Loops

Related Courses

Scala Programming Training Course

Programming Language Course

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Scala Programming Training (3 Courses,1Project) Learn More