Introduction
The replaceAll()
method in Java is a powerful tool for replacing all occurrences of a pattern within a string. Unlike the replace()
method, which only replaces literal characters, replaceAll()
uses regular expressions to identify and replace patterns.
Syntax
public String replaceAll(String regex, String replacement)
Parameters
Parameter | Description |
regex | The regular expression to match. |
replacement | The replacement string. |
Return Value
This method returns a new string with all occurrences of the specified pattern replaced by the given replacement string.
Examples
Example 1: Replacing Spaces with Underscores
Let's start with a simple example. This demonstrates how to replace all spaces in a string with underscores.
String str = "This is a sample string";
String replacedStr = str.replaceAll("\s", "_");
System.out.println(replacedStr);
This_is_a_sample_string
Explanation: The regex "\s"
matches any whitespace character (space, tab, newline, etc.). We replace each occurrence with an underscore.
Example 2: Removing Digits
Here's how to remove all digits from a string using the replaceAll()
method. Imagine you have a product code and want to clean it up by removing numeric characters.
String str = "ProductCode123";
String cleanedStr = str.replaceAll("[0-9]", "");
System.out.println(cleanedStr);
ProductCode
Explanation: The regex "[0-9]"
matches any digit (0 through 9). We replace each digit with an empty string, effectively removing them.
Example 3: Replacing HTML Tags
This example shows how to remove HTML tags from a string. This is useful for sanitizing user-generated content or extracting text from web pages.
String html = "<p>This is some HTML.</p>";
String plainText = html.replaceAll("<[^>]*>", "");
System.out.println(plainText);
This is some HTML.
Explanation: The regex "<[^>]*>"
matches any HTML tag (e.g., <p>
, <b>
). It works by matching the opening bracket (<), then any character that isn't a closing bracket (>) zero or more times ([^>]*), and finally the closing bracket (>). We replace each tag with an empty string.
Example 4: Replacing Multiple Patterns
You can use the pipe symbol (|) in your regular expression to match multiple patterns. This example replaces both 'apple' and 'banana' with 'fruit'.
String str = "I like apple and banana";
String replacedStr = str.replaceAll("apple|banana", "fruit");
System.out.println(replacedStr);
I like fruit and fruit
Explanation: The regex "apple|banana"
matches either 'apple' or 'banana'. The pipe symbol (|) acts as an "or" operator in regular expressions.
Example 5: Using Capturing Groups
Capturing groups allow you to refer back to the matched text within your replacement string. This example replaces dates formatted as MM/DD/YYYY with a standardized format of YYYY-MM-DD.
String dateString = "Date: 12/25/2023";
String replacedDateString = dateString.replaceAll("(\d{2})/(\d{2})/(\d{4})", "$3-$1-$2");
System.out.println(replacedDateString);
Date: 2023-12-25
Explanation: The regex "(\d{2})/(\d{2})/(\d{4})"
captures three groups of digits. The first group ((\d{2})
) matches the month (two digits), the second group ((\d{2})
) matches the day, and the third group ((\d{4})
) matches the year. The replacement string uses $3-$1-$2
to rearrange these captured groups into a new format.