Java String replaceFirst()

The String.replaceFirst() in Java replaces the first occurrence of a substring found that matches the given argument substring (or regular expression) with the specified replacement substring. The substring matching process starts from the beginning of the string (index 0) and ends after the first match is found, else to the end of string.

Note that we can not pass null as method arguments, but we can pass an empty string.

1. String.replaceFirst() Method

The syntax of replaceFirst() is as follows. It searches for substring regex and replaces it with the replacement string. The regex can be a normal string as well as a regular expression.

The replaceFirst() method returns a new string after the first occurrence of the matching regex is replaced with the replacement string.

String replaceFirst(String regex, String replacement);

2. String.replaceFirst() Example

The following Java program replaces the first occurrence of “java” with an uppercase “JAVA” string.

String str = "howtodoinjava";

String newStr = str.replaceFirst("java", "JAVA");

System.out.println(newStr); //howtodoinJAVA

We can also use the regex as follows:

String string = "how to do in java";

String updatedString = string.replaceFirst("\\s", "-");

System.out.println(updatedString); //how-to do in java

3. Escaping Special Characters with Double Backslash

Although we can pass the regex as a substring pattern to match, the original string may contain special characters that we would not want to consider in pattern matching.

In regex, there are characters that have special meaning. These metacharacters are:

\ ^ $ . | ? * + {} [] ()

For such metacharacters, use a double backward slash (\\) to skip that meta character.

String string = "how+to+do+in+java";

String updatedString = string.replaceFirst("\\+", "-");

System.out.println(updatedString); //how-to+do+in+java

4. The ‘null’ is Not Allowed

A 'null' is not allowed as either method argument. The method will throw NullPointerException if null is passed.

String updatedString = string.replaceFirst(null, "-");

Program output.

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "this.pattern" is null

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode