w3resource logo

Introduction to Java Programming

Java String: replaceFirst() Method

Secondary Nav

public String replaceFirst(String regex, String replacement)

The replaceFirst() Method replaces the first substring of this string that matches the given regular expression with the given replacement.

An invocation of this method of the form str.replaceFirst(regex, repl) yields exactly the same result as the expression


Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceFirst(java.lang.String). Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

Java Platform: Java SE 8

Syntax :

replaceFirst(String regex,String replacement)


Name Description Type
regex the regular expression to which this string is to be matched String
replacement the string to be substituted for the first match String

Return Value :The resulting String

Return Value Type: String

PatternSyntaxException - if the regular expression's syntax is invalid

Example : Java String replaceFirst(String regex, String replacement) Method

The following example shows the usage of java String() method.

import java.io.*;
public class Example {

   public static void main(String args[]) {
      String Str = new String("Welcome to example.com");
      System.out.print("Return Value :" );
      System.out.println(Str.replaceFirst("(.*)example(.*)", "java"));

      System.out.print("Return Value :" );
      System.out.println(Str.replaceFirst("example", "java"));


Return Value :java                                     
Return Value :Welcome to java.com 

Java Code Editor :

Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number