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
