Java replaceAll() メソッド
replaceAll() メソッドは、指定された引数 replacement を使用して、指定された正規表現に一致する文字列内のすべての部分文字列を置換します。
構文
public String replaceAll(String regex, String replacement)
パラメータ
regex-- この文字列に一致する正規表現。
replacement-- 各一致項目を置換するために使用される文字列。
戻り値
成功した場合は置換された文字列を返し、失敗した場合は元の文字列を返します。
例
例
public class Test {
public static void main(String args[]) {
String Str = new String("www.google.com");
System.out.print("マッチ成功時の戻り値 :" );
System.out.println(Str.replaceAll("(.*)google(.*)", "サンプル" ));
System.out.print("マッチ失敗時の戻り値 :" );
System.out.println(Str.replaceAll("(.*)taobao(.*)", "サンプル" ));
}
}
public static void main(String args[]) {
String Str = new String("www.google.com");
System.out.print("マッチ成功時の戻り値 :" );
System.out.println(Str.replaceAll("(.*)google(.*)", "サンプル" ));
System.out.print("マッチ失敗時の戻り値 :" );
System.out.println(Str.replaceAll("(.*)taobao(.*)", "サンプル" ));
}
}
上記プログラムの実行結果は次のとおりです:
匹配成功返回值 :サンプル 匹配失败返回值 :www.google.com
その他の拡張
Java String クラス