Java - String replaceFirst() Method



The Java String replaceFirst() method is used to replace the first occurrence of a particular pattern in a String object with the given value.

This method accepts a regular expression and a replacement string as parameters, searches the current string for the pattern that matches the specified regex and, replaces first match with the given replacement string. The process of matching substrings begins from the index 0 which means beginning of the string.

In Java, Strings are objects that a char array supports internally. Strings are a special kind of array that holds characters, since arrays are immutable, it follows that strings are also immutable.

Note − Be aware that if the replacement string contains dollar signs ($) or backslashes (\), the results might not be the same as they would be if they were handled as literal replacement strings.

Syntax

Following is the syntax for Java String replaceFirst() method −

public String replaceFirst(String regex, String replacement)

Parameters

  • regex − This is the regular expression to which this string is to be matched.

  • replacement − This is the string to be substituted for each match.

Return Value

This method returns the resulting string.

Example

The following example shows the usage of Java String replaceFirst() method using regular expression '!!' provided as the substitution substring −

import java.lang.*; 
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "!!Tutorials!!Point", str2;
      String substr = "**", regex = "!!";    
      
      // prints string1
      System.out.println("String = " + str1);    
      
      /* replaces the first substring of this string that matches the given
      regular expression with the given replacement */
      str2 = str1.replaceFirst(regex,substr);    
      System.out.println("After Replacing = " + str2);
   }
}

Output

If you compile and run the above program, it will produce the following result −

String = !!Tutorials!!Point
After Replacing = **Tutorials!!Point

Example

In the code below, we have used the replaceFirst() method to substitute the string '.' for the first substring that matches the regex \d −

public class StringDemo {
   public static void main(String[] args) {
      String s = "Akash 2786 G";
      String s1 = s.replaceFirst("\\d+", ".");
      System.out.println("The new string is: " + s1);
   }
}

Output

If you compile and run the program above, the output will be displayed as follows −

The new string is: Akash . G

Example

A regular expression or a regular string can be used as the first argument for the replaceFirst() method. The reason is that a typical string is a regex of itself.

There are characters in regex that have specific meanings. These are termed as metacharacters. You can escape these characters using ‘\’ if you need to match a substring that contains these metacharacters.

public class StringDemo {
   public static void main(String[] args) {
      String s = "h^k**dg^^kl*^";
      
      // replacing the first "^ with "%"
      String s1 = s.replaceFirst("\\^", "%");
      System.out.println("The replaced string now is: " + s1);
   }
}

Output

On executing the program above, the output is obtained as follows −

The replaced string now is: h%k**dg^^kl*^

Example

Null is not allowed as either of the method arguments. The NullPointerException will be thrown as shown in the following example −

public class StringDemo {
   public static void main(String[] args) {
      String s = "Next time there won't be a next time after a certain time";
      String s1 = s.replaceFirst("Next", null);
      System.out.println("The new string is: " + s1);
   }
}

NullPointerException

The output of the above program is as follows −

Exception in thread "main" java.lang.NullPointerException: replacement
      at java.base/java.util.regex.Matcher.replaceFirst(Matcher.java:1402)
      at java.base/java.lang.String.replaceFirst(String.java:2894)
      at StringDemo.main(StringDemo.java:4)
java_lang_string.htm
Advertisements