Java String.replaceFirst() Method Example

1. Introduction

The String.replaceFirst() method in Java is used to replace the first occurrence of a substring that matches a given regular expression with a specified replacement string. This method is particularly useful for modifying strings when only the first instance of a pattern needs to be changed.

Key Points

- replaceFirst() replaces the first occurrence of a text pattern defined by a regular expression.

- It returns a new string with the first match replaced.

- Useful for targeted text replacements in string processing.

2. Program Steps

1. Declare a string that includes multiple instances of a pattern.

2. Use replaceFirst() to replace the first occurrence of a specific pattern.

3. Print the original and the modified string.

3. Code Program

public class StringReplaceFirstExample {
    public static void main(String[] args) {
        // Original string with repeated words
        String str = "Hello, hello! Are you there, hello?";
        // Replace the first occurrence of 'hello' regardless of case
        String replacedFirst = str.replaceFirst("(?i)hello", "Hi");
        // Print the original and modified strings
        System.out.println("Original string: " + str);
        System.out.println("After replacing the first 'hello': " + replacedFirst);
    }
}

Output:

Original string: Hello, hello! Are you there, hello?
After replacing the first 'hello': Hi, hello! Are you there, hello?

Explanation:

1. String str = "Hello, hello! Are you there, hello?": Declares and initializes a String variable str.

2. String replacedFirst = str.replaceFirst("(?i)hello", "Hi"): Calls replaceFirst() with a regex that matches 'hello' in a case-insensitive manner ((?i) is a regex flag for case insensitivity). The first match is replaced by 'Hi'.

3. The print statements show the string before and after the replacement, illustrating that only the first occurrence of 'hello' has been changed to 'Hi'.


Comments