Java replaceFirst() Method

Java String类Java String Class


The replaceFirst() method uses the given parameter replacement to replace the first substring of the string that matches the given regular expression.

Syntax

public String replaceFirst(String regex,
                           String replacement)

Parameters

  • regex-- The regular expression that matches this string.

  • replacement-- The string used to replace the first match.

Return Value

Returns the replaced string on success, and the original string on failure.

Example

public class Test {
    public static void main(String args[]) {
        String Str = new String("hello example,I am from example。");

        System.out.print("返回值 :" );
        System.out.println(Str.replaceFirst("example", "google" ));
        System.out.print("返回值 :" );
        System.out.println(Str.replaceFirst("(.*)example(.*)", "google" ));
    }
}

The result of executing the above program is:

返回值 :hello google,I am from example。
返回值 :google

Java String类Java String Class

Other Extensions