logo

Java String ReplaceFirst() Method


Show

Description

This way returns the first substring of this thread that competitions the given normal expression with the agreed replacement.

Syntax

Here is the syntax of this method:

public String replaceFirst(String regex, String replacement)

Parameters

Here is the detail of parameters −

  • regex − the regular expression to which this string is to be matched.
  • replacement − − the string which would replace found expression.

Return Value

  • This method returns the resulting String.

Example

import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Intellinuts.com");

      System.out.print("Return Value :" );
      System.out.println(Str.replaceFirst("(.*)Nuts(.*)", "SMROOD"));

      System.out.print("Return Value :" );
      System.out.println(Str.replaceFirst("Nuts", "SMROOD"));
   }
}

This will produce the following result:

Output

Return Value :SMROOD
Return Value :Welcome to IntelliSMROOD.com

Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.