Java Matcher replaceFirst() Method
Example
Replace the first number in a sentence with a word:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher("The binary representation of 5 is 101.");
System.out.println(matcher.replaceFirst("five"));
}
}
Definition and Usage
The replaceFirst() method replaces the first match of the pattern with a new text, and returns the result as a new string. The original text is not changed.
In the example, [0-9]+ means "one or more digits from 0 to 9". Only the first number is replaced.
Tip: Use the replaceAll() method to replace every match.
Syntax
public String replaceFirst(String replacement)
Parameter Values
| Parameter | Description |
|---|---|
| replacement | Required. The text to put in place of the first match. |
Technical Details
| Returns: | A new String where the first match is replaced. |
|---|
Related Pages
❮ RegEx Methods