Home »
Scala
Scala String replaceAll() Method with Example
Here, we will learn about the replaceAll() method in Scala. The replaceAll() method is used to find and replace the all occurrence of the given string in Scala.
Submitted by Shivang Yadav, on January 29, 2021
String is an immutable collection that stores sequences of characters.
String replaceAll() Method
The replaceAll() method on strings is used to replace all occurrences of the given substring with another string. The substring to be replaced can be a proper string or a pattern to be matched.
Syntax:
string.replaceAll(replaceString, newString)
Parameters: The method accepts two parameters; one is the substring to be replaced and other is the string which is going to replace the substring.
Return Value: It returns a string which is the string created after performing the replace operation.
Example 1: Replace all method, search for a perfect substring
object myObject {
def main(args: Array[String]) {
val myString = "Scala Programming language"
println("The string is ' " + myString + "'")
val newString = myString.replaceAll("a", "*")
println("The string after replace operation '" + newString + "'")
}
}
Output:
The string is ' Scala Programming language'
The string after replace operation 'Sc*l* Progr*mming l*ngu*ge'
Example 2: Replace all method, search for a pattern match
object myObject {
def main(args: Array[String]) {
val myString = "Scala Programming language"
println("The string is ' " + myString + "'")
val newString = myString.replaceAll(".a", "**")
println("The string after replace operation '" + newString + "'")
}
}
Output:
The string is ' Scala Programming language'
The string after replace operation 'S**** Prog**mming **ng**ge'