Java String replaceFirst()

The syntax of the replaceFirst() method is:

string.replaceFirst(String regex, String replacement)

Here, string is an object of the String class.


replaceFirst() Parameters

The replaceFirst() method takes two parameters.

  • regex - a regex (can be a typical string) that is to be replaced
  • replacement - the first matching substring is replaced with this string

replaceFirst() Return Value

  • The replaceFirst() method returns a new string where the first occurrence of the matching substring is replaced with the replacement string.

Example 1: Java String replaceFirst()

class Main {
  public static void main(String[] args) {
      String str1 = "aabbaaac";
      String str2 = "Learn223Java55@";

      // regex for sequence of digits
      String regex = "\\d+";

      // the first occurrence of "aa" is replaced with "zz"
      System.out.println(str1.replaceFirst("aa", "zz")); // zzbbaaac

      // replace the first sequence of digits with a whitespace
      System.out.println(str2.replaceFirst(regex, " ")); // Learn Java55@
  }
}

In the above example, "\\d+" is a regular expression that matches a sequence of digits.


Escaping Characters in replaceFirst()

The replaceFirst() method can take a regex or a typical string as the first argument. It is because a typical string in itself is a regex.

In regex, there are characters that have special meaning. These metacharacters are:

\ ^ $ . | ? * + {} [] ()

If you need to match substring containing these metacharacters, you can escape these characters using \.

// Program to the first + character
class Main {
  public static void main(String[] args) {
    String str = "a+a-++b";

    // replace the first "+" with "#"
    System.out.println(str.replaceFirst("\\+", "#")); // a#a-++b

  }
}

Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community