Java replaceFirst() Method
The replaceFirst() method uses the given replacement parameter to replace the first substring of the string that matches the given regular expression.
Syntax
public String replaceFirst(String regex,
String replacement)
Parameters
-
regex -- The regular expression that matches this string.
-
replacement -- The string used to replace the first match.
Return Value
Returns the replaced string on success, or the original string on failure.
Example
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" ));
}
}
The execution result of the above program is:
返回值 :hello google,I am from runoob。
返回值 :google
Java String class