Scala Regex | Scala Regular Expressions – Replacing Matches

Scala course with real-time projects Start Now!!

In our last tutorial, we studied Scala Trait Mixins. Today, we are going to discuss Scala Regular Expressions or in general terms, we call it Scala Regex. In this Scala Regex cheat sheet, we will learn syntax and example of Scala Regular Expression, also how to Replace Matches and Search for Groups of Scala Regex.

So, let’s begin Scala Regular Expression (Regex).

What is Scala Regex?

We now move on to regular expressions. Using certain strings, we can find patterns and lack of patterns in data.’ To convert a string into a regular expression, use the .r method. We import the Regex class from the package scala.util.matching.Regex.
Let’s Discuss Scala Closures with Examples 

scala> val word="portmanteau".r
word: scala.util.matching.Regex = portmanteau
scala> val str=" Scala is a portmanteau of scalable and language"
str: String = Scala is a portmanteau of scalable and language
scala> word findFirstIn str
res9: Option[String] = Some(portmanteau)

Here, Scala converts the String to a RichString and invokes r() for an instance of Regex. We define a word and a string to search in. Then, we call the method findFirstIn() to find the first match. For a string with multiple occurrences, we can use findAllIn() to find all occurrences.

Scala Regular Expressions Example

Let’s take another example of Scala Regex.

scala> import scala.util.matching.Regex
import scala.util.matching.Regex
scala> val word=new Regex("(i|I)ntern")
word: scala.util.matching.Regex = (i|I)ntern
scala> val str="An intern on the Internet"
str: String = An intern on the Internet
scala> (word findAllIn str).mkString(", ")
res10: String = intern, Intern

Here, we use the Regex() constructor to create the pattern, the method findAllIn() to find all occurrences of the word, and a pipe(|) to allow any case of a certain letter.

How to Replace Matches in Scala Regex?

To replace a first match, we use the method replaceFirstIn(). To replace all matches, we use replaceAllIn().

scala> val word="Python".r
word: scala.util.matching.Regex = Python
scala> val str="I'm doing Python"
str: String = I'm doing Python
scala> word replaceFirstIn(str,"Scala")
res11: String = I'm doing Scala

Searching for Groups of Scala Regular Expression

We can use parentheses to search for groups of regular expressions in Scala.

scala> val pattern="([0-9a-zA-Z-#() ]+): ([0-9a-zA-Z-#() ]+)".r
pattern: scala.util.matching.Regex = ([0-9a-zA-Z-#() ]+): ([0-9a-zA-Z-#() ]+)
scala> val str=
| """background-color: #A03300;
| background-image: url(img/header100.png);
| background-position: top center;
| background-repeat: repeat-x;
| background-size: 2160px 108px;
| margin: 0;
| height: 108px;
| width: 100%;""".stripMargin
str: String =
background-color: #A03300;
background-image: url(img/header100.png);
background-position: top center;
background-repeat: repeat-x;
background-size: 2160px 108px;
margin: 0;
height: 108px;
width: 100%;
scala> for(patternMatch<-pattern.findAllMatchIn(str))
| println(s"key:${patternMatch.group(1)} value:${patternMatch.group(2)}")
key:background-color value:#A03300
key:background-image value:url(img
key:background-position value:top center
key:background-repeat value:repeat-x
key:background-size value:2160px 108px
key:margin value:0
key:height value:108px
key:width value:100

Let’s study Inheritance in Java Programming Language 

The syntax of Scala Regex

Where Java inherits many features from Perl, Scala inherits the syntax of Scala regular expressions from Java. Here’s the list of metacharacter syntax:

Subexpression

Matches

^

Beginning of line

$

End of line

.

Single character; with option m, matches newline too

[…]

Single character in square brackets

[^…]

Single character not in square brackets

\\A

Beginning of string

\\z

End of string

\\Z

End of string except allowable final line terminator

re*

Zero or more occurrences of preceding expression

re+

One or more occurrences of preceding expression

re?

Zero or one occurrences of preceding expression

re{ n}

n occurrences of preceding expression

re{ n,}

n or more occurrences of preceding expression

re{ n, m}

At least n, at most m occurrences of preceding expression

a|b

Either a or b

(re)

Groups regular expressions; remembers matched text

(?: re)Scala Regex

Groups regular expressions; doesn’t remember matched text

(?> re)

Independent pattern; doesn’t backtrack

\\w

Word characters

\\W

Nonword characters

\\s

Whitespace; equivalent to [\t\n\r\f]

\\S

Nonwhitespace

\\d

Digits; equivalent to [0-9]

\\D

Nondigits

\\A

Beginning of string

\\Z

End of string; matches till before newline, if any

\\z

End of string

\\G

Point where last match ended

\\n

Beck-reference to capture group number ‘n’

\\b

Word boundaries when outside brackets; backspace (0x08) when inside brackets

\\B

Nonword boundaries

\\n, \\t,etc.

Newlines, carriage returns, tabs, and so

\\Q

Escape (quote) all characters up to \\E

\\E

Ends quoting begun with \\Q

Let’s Learn Scala Inheritance – Syntax, Example & Types in Detail

So, this was all about Scala Regex Tutorial. Hope you like our explanation.

Conclusion

Hence, in this Scala regex cheat sheet, we studied what is Scala Regular expression. In addition, we saw example & syntax of Scala Regex and how to Replace Matches and Search for Groups of Scala Regular Expression. Furthermore, if you have a query regarding, feel free to ask in the comment box.

See Also- Scala Final | Scala This

Reference

Your opinion matters
Please write your valuable feedback about DataFlair on Google

courses

DataFlair Team

The DataFlair Team provides industry-driven content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our expert educators focus on delivering value-packed, easy-to-follow resources for tech enthusiasts and professionals.

Leave a Reply

Your email address will not be published. Required fields are marked *