liveBook · Manning

replaceAll method

As explained in 100 Java Mistakes and How to Avoid Them

The Java String.replaceAll method returns a string in which substrings matching a regular expression are replaced with a replacement string.

String.replaceAll returns a string in which substrings matching a regular expression are replaced. The common mistake is treating it like replace: both replace all occurrences, but replace accepts literal text while replaceAll accepts a regex. section 6.6

A replacement string is not always plain text

In template code such as template.replaceAll("USER_NAME", user), a username of "$0ccerman" can produce "Hello USER_NAMEccerman!" because $0 expands to the complete match. A username containing "$1" can instead cause IndexOutOfBoundsException when the pattern has no matching group. section 6.6

Avoid the mistake with these checks:

  • Use replace when the search value is literal; use replaceFirst when only the first regex match should change. section 6.6
  • Treat externally supplied search text as a regex with replaceAll, and remember that replacement text interprets sequences such as $0 and $1. section 6.11 section 6.6
  • Prefer replace for literal substitutions when possible; modern Java versions make it significantly faster than replaceAll. section 6.6

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains method distinctions, regex and replacement semantics, failure cases, and safer method choices without detailing regex internals.
Examples
Uses a greeting template, usernames containing $0 or $1, and a mistaken replaceAll call.
What it assumes
Assumes familiarity with Java strings and method calls while clarifying replace, replaceAll, and replaceFirst from their shared two-argument shape.
What you can do after
Apply it via Java String APIs while choosing literal or regex replacement deliberately and checking replacement-string metacharacters.
How it connects
Connects regular expressions with replace, replaceFirst, replacement groups, external input, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.