Java String replaceFirst() Method
Example
Replace the first match of a regular expression with a different substring:
String myStr = "This is W3Schools";
String regex = "is";
System.out.println(myStr.replaceFirst(regex, "at"));
Definition and Usage
The replaceFirst()
method replaces the first match of a regular expression in a string with a new substring.
Replacement strings may contain a backreference in the form $n where n is the index of a group in the pattern. In the returned string, instances of $n will be replaced with the substring that was matched by the group or, if $0 is used, by the whole expression. See "More Examples" below for an example of using a backreference.
Tip: See the Java RegEx tutorial to learn about regular expressions.
Syntax
public String replaceFirst(String regex, String replacement)
Parameter Values
Parameter | Description |
---|---|
regex | Required. A regular expression defining what substrings to search for. |
replacement | Required. The substring which will replace the first match. |
Technical Details
Returns: | A copy of the string in which the first substring that matches the regular expression is replaced with a new substring. |
---|---|
Throws: | PatternSyntaxException - If the syntax of the regular expression is incorrect. |
Java version: | 1.4 |
More Examples
Example
Use a backreference to wrap the first number in parentheses:
String myStr = "Quest complete! Earned 30 gold and 500 experience.";
String regex = "[0-9]+";
System.out.println(myStr.replaceFirst(regex, "($0)"));
❮ String Methods