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 passedregex.
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
replaceFirstmethod withregexasxyzand replacement string asEducative. -
The
replaceFirstmethod replaces the first substring that matches theregexpassed with theEducativestring, and returns the replaced string as a new String. -
So, the
replaceFirstmethod 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 -.
Points to note
-
The
replaceFirstmethod will only replace the first match for the regex. -
If no match for the passed
regexis found, then the source string is returned. -
We will get
NullPointerExceptionif we passnullas the replacement string. -
If we want to match the below
:metacharacters characters 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 -.