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 サンプル,I am from サンプル。");
System.out.print("返回值 :" );
System.out.println(Str.replaceFirst("サンプル", "google" ));
System.out.print("返回值 :" );
System.out.println(Str.replaceFirst("(.*)サンプル(.*)", "google" ));
}
}
上記のプログラムの実行結果は次のとおりです:
返回值 :hello google,I am from サンプル。 返回值 :google
その他の拡張
Java Stringクラス