Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java replaceFirst() Method

Java replaceFirst() Method

Java String ClassJava String class


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

Syntax


public String replaceFirst(String regex,
                           String replacement)

Parameters

Return Value

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

Example


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

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

The execution result of the above program is:


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

Java String ClassJava String class