String replaceFirst(String regex, String replacement) method in Java

The replaceFirst(String regex, String replacement) method in Java replaces the first substring of this string that matches the given regular expression with the given replacement.

Syntax

Let us see the syntax,

String replaceFirst(String regex, String replacement)

Parameters

Let us see the parameters,

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

Example

The following is an example of replaceFirst(String regex, String replacement),

public class StudyopediaDemo {

   public static void main(String args[]) {
	 
      String message = new String("Studyopedia provides free learning content!");
      System.out.println("String: "+message);
	  
      System.out.print("Result after replacing: " );
      System.out.println(message.replaceFirst("content", "tutorials"));
  } 
}

Output

The following is the output,

Java replacefirst string method

String replaceAll(String regex, String replacement) method in Java
String split(String regex) method in Java
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment