Facebook Page Twitter Page LinkedIn Page
× Java Tutorial Java Advanced Java Resources


The Java string replaceFirst() method is used to return the string with first occurrence of the specified regular expression replaced with specified string in the given string.

Syntax

public String replaceFirst(String regex,
                           String replacement)

Parameters

regex specify the regular expression to which this string is to be matched.
replacement specify the string to be substituted for first match.

Return Value

Returns the replaced version of the specified string.

Exception

throws PatternSyntaxException, if the regular expression's syntax is invalid.

Example:

In the below example, replaceFirst() method to used to return the string where first occurrence of the specified regular expression is replaced with specified string in the given string called MyString.

public class MyClass {
  public static void main(String[] args) {
    String MyString = "Hello Hullo";
    
    //first l is replaced with k
    String NewString1 = MyString.replaceFirst("l", "k");
    //printing new string
    System.out.println(NewString1);

    //first ll is replaced with kl
    String NewString2 = MyString.replaceFirst("ll", "kk");
    //printing new string
    System.out.println(NewString2);
  }
}

The output of the above code will be:

Heklo Hullo
Hekko Hullo

❮ Java String Methods