java.lang.String replaceFirst()

Description :

This java tutorial shows how to use the replaceFirst() method of java.lang.String class. This method returns a new String object as a result of replacing the first occurence of characters as defined on our method argument if the regex pattern is found.

Method Syntax :

public String replaceFirst(String regex,String replacement)

Parameter Input :

String|regex|Regular expression that we have to use on evaluation if our string qualifies to be reconstructed by replacing characters.
String|replacement|The string to be replaced on our String once the regex pattern satisfies our method search

Method Returns :

This method returns a new String object resulting from the replacement of characters defined on method argument on the first occurrence of the regex pattern.

Compatibility Version :

Requires Java 1.4 and up

Exception :


This exception will be thrown if and only if the parameter CharSequence s is null.

Discussion :

The replaceFirst() method of String class is basically being used to replace the first occurrence of the specified regular expression by the replacement string. This is very helpful in dealing with string replacements and we want only to replace the first occurrence.

Java Code Example :

This example source code demonstrates the use of contains() method of String class. Basically we have a parent string “This is a demo” and as specified on the method argument of the replacefirst method the string “is” will be replace by “”. So this example intention is to remove the first occurence of “is” string. You might have guessed the result would be “This a demo” which is incorrect. Remember that we will be replacing the first occurrence of “is” string and that would be found on “this“. So the result should be “Th is a demo”.

Sample Output :

Running the contains() method example source code of java.lang.String class will give you the following output 

string replacefirst method example

string replacefirst method example

Exception Scenario :

Suggested Reading List :