Java String ReplaceAll and ReplaceFirst Fails at $ Symbol at Replacement Text
In a replacement string, $
is a special character: it is used to grab matched groups from the pattern you are replacing. You can read more about it here.
To fix this, you can quote the replacement string to remove all special meaning from $
characters:
import java.util.regex.Matcher;
// ...
String output = template.replaceAll(pattern, Matcher.quoteReplacement("$ 100"));
String.replaceAll
takes a regular expression matching pattern as its first parameter, and a regular expression replacement pattern as its second parameter - and $
has a specific meaning in regular expressions (in both matching patterns and replacement patterns, although in different senses).
Just use String.replace
instead, and I suspect all your problems will go away. You should only use replaceAll
when you genuinely want to match/replace via a regular expression - which I don't think you do in this case.
EDIT: As to your question:
What is the problem with having a special symbol in the replacement text (not in the regex)?
Again, the documentation for replaceAll
makes this clear:
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see
Matcher.replaceAll
. UseMatcher.quoteReplacement(java.lang.String)
to suppress the special meaning of these characters, if desired.
So if you want to treat the matching pattern as a regular expression, but not the replacement, then use Matcher.quoteReplacement
.