Substitute the initial occurrence of a regular expression match with a distinct substring.
String |
The replaceFirst() method in Java replaces the initial match of a regular expression within a string with a new substring.
In replacement strings, you can include a backreference as $n, where n represents the index of a group in the pattern. In the resulting string, occurrences of $n will be substituted with the substring matched by the respective group. Alternatively, using $0 will replace it with the entire expression. Refer to “More Examples” below for an illustration of using a backreference.
Hint: Consult the Java RegEx tutorial to grasp regular expressions.
public String replaceFirst(String regex, String replacement) |
Parameter |
Description |
regex |
Necessary: a regular expression that specifies the substrings to be sought. |
replacement |
Mandatory: the substring that will substitute the first match. |
Returns: |
A duplicated string where the initial substring matching the regular expression is substituted with a new substring. |
Throws: |
PatternSyntaxException occurs if there is a syntax error in the regular expression. |
Java Version: |
1.4 |
Employ a backreference to enclose the initial number within parentheses.
String |