Java replaceFirst() 方法

Java String類Java String類


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 zaixian,I am from zaixian。");

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

以上程式執行結果為:

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

返回值 :google

Java String類Java String類