Open In App

Scala String replaceFirst() method with example

Last Updated : 03 Oct, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads