replaceAll: Regex-Based Replacement
You'll learn how to use replaceAll() to find and replace multiple occurrences using powerful pattern matching.
What is replaceAll?
While replace() works with literal character sequences, replaceAll(String regex, String replacement) leverages regular expressions (regex) to match patterns in your string. Think of it as a find-and-replace tool where you can describe what kind of text to find, not just exact matches.
The method scans the entire string, finds all substrings matching the regex pattern, and replaces each one with your replacement string.
How It Works
String text = "My phone: 123-456-7890";
String masked = text.replaceAll("\\d", "*");
// Result: "My phone: ***-***-****"
Here, \\d is a regex pattern matching any digit. Every single digit gets replaced with *.
Pattern Power Examples
String messy = "Hello World Java";
String clean = messy.replaceAll("\\s+", " ");
// Result: "Hello World Java" (multiple spaces → single space)
String code = "varName123";
String letters = code.replaceAll("[0-9]", "");
// Result: "varName" (removes all digits)
String html = "<p>Hello</p>";
String plain = html.replaceAll("<.*?>", "");
// Result: "Hello" (strips HTML tags)
Important Notes
- The first parameter is a regex, not literal text. Special characters like
.,*,+have special meanings. - To match literal special characters, escape them:
replaceAll("\\.", "!")replaces periods. - All matches are replaced, not just the first (unlike
replaceFirst()). - Returns a new string; the original remains unchanged.
Key Takeaway: replaceAll() combines the power of pattern matching with replacement, enabling sophisticated string transformations that go far beyond simple literal substitution.