The syntax of the replaceFirst() method is:
string.replaceFirst(String regex, String replacement)
Here, string is an object of the String class.
replaceFirst() Parameters
The replaceFirst() method takes two parameters.
- regex - a regex (can be a typical string) that is to be replaced
- replacement - the first matching substring is replaced with this string
replaceFirst() Return Value
- The
replaceFirst()method returns a new string where the first occurrence of the matching substring is replaced with the replacement string.
Example 1: Java String replaceFirst()
In the above example, "\\d+" is a regular expression that matches a sequence of digits. To learn more, visit Java regex.
Escaping Characters in replaceFirst()
The replaceFirst() method can take a regex or a typical string as the first argument. It is because a typical string in itself is a regex.
In regex, there are characters that have special meaning. These metacharacters are:
\ ^ $ . | ? * + {} [] ()
If you need to match substring containing these metacharacters, you can escape these characters using \.
If you need to replace each substring that matches the regex, use the Java String replaceAll() method.