Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
HowToDoInJava
  • Java
  • Spring AI
  • Spring Boot
  • Hibernate
  • JUnit 5
  • Interview

Java String replaceFirst()

Java String.replaceFirst() replaces the first occurrence of a substring found that matches the given argument substring (or regex).

Lokesh Gupta

October 11, 2023

Java String class
Java String
Java String

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
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

String Examples

  • String Constant Pool
  • Convert String to int
  • Convert int to String
  • Convert String to long
  • Convert long to String
  • Convert CSV String to List
  • Java StackTrace to String
  • Convert float to String
  • Align Left, Right, Center
  • Immutable Strings
  • StringJoiner
  • Split a string
  • Escape HTML
  • Unescape HTML
  • Convert to title case
  • Find duplicate words
  • Left pad a string
  • Right pad a string
  • Reverse recursively
  • Leading whitespaces
  • Remove whitespaces
  • Reverse words
  • Find duplicate characters
  • Get first 4 characters
  • Get last 4 characters
  • (123) 456-6789 Pattern
  • Interview Questions

String Methods

  • String concat()
  • String hashCode()
  • String contains()
  • String compareTo()
  • String compareToIgnoreCase()
  • String equals()
  • String equalsIgnoreCase()
  • String charAt()
  • String indexOf()
  • String lastIndexOf()
  • String intern()
  • String split()
  • String replace()
  • String replaceFirst()
  • String replaceAll()
  • String substring()
  • String startsWith()
  • String endsWith()
  • String toUpperCase()
  • String toLowerCase()

Table of Contents

  • 1. String.replaceFirst() Method
  • 2. String.replaceFirst() Example
  • 3. Escaping Special Characters with Double Backslash
  • 4. The ‘null’ is Not Allowed
Photo of author

Lokesh Gupta

A fun-loving family man, passionate about computers and problem-solving, with over 15 years of experience in Java and related technologies. An avid Sci-Fi movie enthusiast and a fan of Christopher Nolan and Quentin Tarantino.
Follow on Twitter Portfolio

Previous

Java String replace()

Next

Java String replaceAll()

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.

Tutorial Series

OOP

Regex

Maven

Logging

TypeScript

Python

Meta Links

About Us

Advertise

Contact Us

Privacy Policy

Our Blogs

REST API Tutorial

Follow On:

  • Github
  • LinkedIn
  • Twitter
  • Facebook
Copyright © 2026 | Sitemap