The replaceFirst() method is same as replaceAll but here only the first appearance of the stated sub-string will be replaced.
Method Definition: String replaceFirst(String regex, String replacement)
Return Type: It returns the stated string after replacing the first appearance of stated regular expression with the string we provide.
Example #1:
// Scala program of replaceFirst() // method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Applying replaceFirst method
val result = "csoNidhimsoSingh" .replaceFirst( ".so" , "##" )
// Displays output
println(result)
}
} |
Output:
##NidhimsoSingh
Example #2:
// Scala program of replaceFirst() // method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Applying replaceFirst method
val result = "NidhimsoSinghcso" .replaceFirst( ".so" , "*" )
// Displays output
println(result)
}
} |
Output:
Nidhi*Singhcso
Example #3:
// Scala program of replaceFirst() // method // Creating object object GfG
{ // Main method
def main(args : Array[String])
{
// Applying replaceFirst method
val result = "fsoNidhimsoSinghcso" .replaceFirst( ".so" , "*" )
// Displays output
println(result)
}
} |
Output:
*NidhimsoSinghcso