1. 程式人生 > >java:replaceFirst() 方法

java:replaceFirst() 方法

replaceFirst() 方法使用給定的引數 replacement 替換字串第一個匹配給定的正則表示式的子字串。

語法

public String replaceFirst(String regex,
                           String replacement)

引數

  • regex -- 匹配此字串的正則表示式。

  • replacement -- 用來替換第一個匹配項的字串。

返回值

成功則返回替換的字串,失敗則返回原始字串。

 例項:

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" ));
    }
}
返回值 :hello google,I am from runoob。
返回值 :google