Java String replaceAll() Method Example

1. Introduction

The String.replaceAll() method in Java replaces each substring of this string that matches the given regular expression with the given replacement. This method is extremely useful in scenarios involving text processing where pattern matching is required, such as formatting or data cleaning.

Key Points

- replaceAll() uses regular expressions to identify substrings for replacement.

- The method returns a new string resulting from replacing every matched substring.

- It throws PatternSyntaxException if the regex syntax is invalid.

2. Program Steps

1. Declare a string containing text that will be modified.

2. Use replaceAll() to replace spaces with underscores.

3. Use replaceAll() to replace punctuation with an exclamation mark.

4. Print the original and modified strings.

3. Code Program

public class StringReplaceAllExample {
    public static void main(String[] args) {
        // Original string
        String str = "Hello, world! Welcome to Java.";
        // Replace all spaces with underscores
        String replacedSpaces = str.replaceAll(" ", "_");
        // Replace all punctuation with exclamation marks
        String replacedPunctuation = str.replaceAll("[,!.]", "!");
        // Print the results
        System.out.println("Original string: " + str);
        System.out.println("After replacing spaces with underscores: " + replacedSpaces);
        System.out.println("After replacing punctuation with exclamation marks: " + replacedPunctuation);
    }
}

Output:

Original string: Hello, world! Welcome to Java.
After replacing spaces with underscores: Hello,_world!_Welcome_to_Java.
After replacing punctuation with exclamation marks: Hello! world! Welcome to Java!

Explanation:

1. String str = "Hello, world! Welcome to Java.": Declares and initializes a String variable str.

2. String replacedSpaces = str.replaceAll(" ", "_"): Uses replaceAll() to change all spaces to underscores using a simple space character pattern.

3. String replacedPunctuation = str.replaceAll("[,!.]", "!"): Uses replaceAll() to change all commas, periods, and exclamation marks to exclamation marks using a regular expression that matches punctuation.

4. The print statements display the original string and its variations after replacements.


Comments