Java String: replaceFirst() Method
public String replaceFirst(String regex, String replacement)
The replaceFirst() Method replaces the first substring of this string that matches the given regular expression with the given replacement.
An invocation of this method of the form str.replaceFirst(regex, repl) yields exactly the same result as the expression
Pattern.compile(regex).matcher(str).replaceFirst(repl)
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceFirst(java.lang.String). Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.
Java Platform: Java SE 8
Syntax:
replaceFirst(String regex,String replacement)
Parameters:
Name | Description | Type |
---|---|---|
regex | the regular expression to which this string is to be matched | String |
replacement | the string to be substituted for the first match | String |
Return Value:The resulting String
Return Value Type: String
Throws:
PatternSyntaxException - if the regular expression's syntax is invalid
Example: Java String replaceFirst(String regex, String replacement) Method
The following example shows the usage of java String() method.
import java.io.*;
public class Example {
public static void main(String args[]) {
String Str = new String("Welcome to example.com");
System.out.println();
System.out.print("Return Value :" );
System.out.println(Str.replaceFirst("(.*)example(.*)", "java"));
System.out.print("Return Value :" );
System.out.println(Str.replaceFirst("example", "java"));
System.out.println();
}
}
Output:
Return Value :java Return Value :Welcome to java.com
Java Code Editor :
Previous:replaceAll Method
Next:split Method
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-tutorial/string/string_replacefirst.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics