Java String replaceFirst() Method

Java String replaceFirst() Method | In this blog, we will discuss the replaceFirst() method. It is a built-in method in Java that enables us to replace the first occurrence of the given regular expression which can be a character or a substring. In some cases there might a situation where we need to change some or one occurrence of the character in that case we can use the replaceFirst() method.

The replaceFirst() method is the variant of the replace() method the only difference is, that the replace() method replaces all the occurrences of the character or the sub-string but the replaceFirst() method only replaces the first occurrence. Apart from replace(), and replaceFirst() method, the Java string class also contains replaceAll() method. Let us see some Java string replaceFirst() examples:-

String = “vacation”
Replace first ‘a’ with ‘o’
After replacement, the string will be: “vocation”.

The method signature for String replaceFirst() Java is:-
public String replaceFirst(String regex, String substring)

Parameters:
Regex:- the regular expression which needs to be replaced
Substring:- the substring which will be placed.
Return Type: String
Returns:- a string after replacement.

Java String replaceFirst() Example

Now let us see some examples of the String replaceFirst() method. In the given string it will replace only the first occurrence of the given sub-string or character.

public class Main {
   public static void main(String[] args) {
      String string1 = "aaaabbbbaaaaaaccc";
      String string2 = "Java Programming";
      String str = "\\d+";

      System.out.println(string1.replaceFirst("aaaa", "zzzz"));
      System.out.println(string2.replaceFirst(str, " "));
   }
}

Output:-

zzzzbbbbaaaaaaccc
Java Programming

Java String replaceFirst() Example

public class Main {

   public static void main(String args[]) {
      String string = new String("Hi all, Goog morning..!");

      System.out.print("Return Value: ");
      System.out.println(string.replaceFirst("(.*)Goog(.*)", "Good"));

      System.out.print("Return Value: ");
      System.out.println(string.replaceFirst("Goog", "Good"));
   }
}

Output:-

Return Value: Good
Return Value: Hi all, Good morning..!

We have called replaceFirst(“(.*)Goog(.*)”, “Good”) so it will find the sub-string containing “Goog” and replace the entire sub-string with “Good”. Therefore the result value is “Good”.

public class Main {
   public static void main(String[] args) {
      String string = "Hello ##ople";
      System.out.println(string.replaceFirst("#", "P"));
   }
}

Output:-

Hello P#ople

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *