What is String.replaceFirst() method in Java?

The String.replaceFirst(regex, replacementString) method replaces the first sub-string that matches the passed regex with the replacementString, and returns it as a new String object.

Syntax

stringObj.replaceFirst(regex, replacementStrnig)
  • regex: The regex to be searched in the String.
  • replacementString: The string which is to be replaced for a substring that matches the passed regex.

Example 1

class ReplaceStringExample {
public static void main(String[] args) {
String str = "Learn more at xyz.com";
//Replace xyz.com with "Educative.com"
String newStr = str.replaceFirst("xyz", "Educative");
System.out.println(newStr);
}
}

In the code above, we have:

  • Created a String "Learn more at xyz.com"

  • Called the replaceFirst method with regex as xyz and replacement string as Educative.

  • The replaceFirst method replaces the first substring that matches the regex passed with the Educative string, and returns the replaced string as a new String.

  • So, the replaceFirst method will return “Learn more at Educative.com.

Example 2

class ReplaceStringExample {
public static void main(String[] args) {
String str = "Jonny 1123 D";
String newStr = str.replaceFirst("\\d+", "-");
System.out.println(newStr);
}
}

In the code above, we have used the replaceFirst method to replace the first substring which matches the regex \dregular expression that matches a sequence of numbers. with the replacement string -.


Points to note

  • The replaceFirst method will only replace the first match for the regex.

  • If no match for the passed regex is found, then the source string is returned.

  • We will get NullPointerException if we pass null as the replacement string.

  • If we want to match the below metacharacterscharacters which have special meaning in a regex. For example, . – any character:

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

then, we need to use \ to escape the characters. For example, to match ., we need to use \\.

class ReplaceStringExample {
public static void main(String[] args) {
String str = "Educative.io";
String newStr = str.replaceFirst("\\.", "-");
System.out.println(newStr);
}
}

In the code above, we have use the regex \\. to match the . in the string. Then, the matched substring is replaced with -.

Free Resources