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 :

DataType Parameter Description
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”.


 * example source code to replace a string
 * with respect to regex patter on the input argument

public class ReplaceFirstDemo {

    public static void main(String[] args) {
        String parentString = "This is a demo";
        System.out.println(parentString.replaceFirst("is", ""));



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 :

Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
	at java.util.regex.Pattern.error(Unknown Source)
	at java.util.regex.Pattern.sequence(Unknown Source)
	at java.util.regex.Pattern.expr(Unknown Source)
	at java.util.regex.Pattern.compile(Unknown Source)
	at java.util.regex.Pattern.(Unknown Source)
	at java.util.regex.Pattern.compile(Unknown Source)
	at java.lang.String.replaceFirst(Unknown Source)

Suggested Reading List :