Java replaceAll() Method
The replaceAll() method uses the given parameter replacement to replace all substrings of the string that match the given regular expression.
Syntax
public String replaceAll(String regex, String replacement)
Parameters
regex-- The regular expression that matches this string.
replacement-- The string used to replace each matching substring.
Return Value
Returns the replaced string if successful, or the original string if failed.
Example
Example
public class Test {
public static void main(String args[]) {
String Str = new String("www.google.com");
System.out.print("Return value on successful match:" );
System.out.println(Str.replaceAll("(.*)google(.*)", "example" ));
System.out.print("Return value on failed match:" );
System.out.println(Str.replaceAll("(.*)taobao(.*)", "example" ));
}
}
public static void main(String args[]) {
String Str = new String("www.google.com");
System.out.print("Return value on successful match:" );
System.out.println(Str.replaceAll("(.*)google(.*)", "example" ));
System.out.print("Return value on failed match:" );
System.out.println(Str.replaceAll("(.*)taobao(.*)", "example" ));
}
}
The result of executing the above program is:
匹配成功返回值 :example 匹配失败返回值 :www.google.com
Other Extensions
Java String Class