Java Tutorial Java Advanced Java References

Java String - replaceFirst() Method



The Java replaceFirst() method returns 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 example below, replaceFirst() method returns 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