Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matcher.replaceAll - Chokes on $,\ in replacement String

Tags:

java

regex

So I just ran into the nice edge case where doing a replaceAll on a String will choke if the replacement String has a $ or \ in it.

Why is the replacement String not just a drop in replace for matches with the regular expression I dictate? What am I not understanding about regular expressions here?

Quote from Oracle Java 7 Documentation:

public String replaceAll(String replacement)

Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.

This method first resets this matcher. It then scans the input sequence looking for matches of the pattern. Characters that are not part of any match are appended directly to the result string; each match is replaced in the result by the replacement string. The replacement string may contain references to captured subsequences as in the appendReplacement method.

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. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

like image 628
thatidiotguy Avatar asked Aug 03 '26 21:08

thatidiotguy


2 Answers

The dollar sign is a special character; you must escape it:

"\\$"

Note the double backslash - that's how you code a single backslash in java, which means \$ is passed to the replace method.

A dollar sign indicates a back reference to a captured group:

"$1" // replace with group 1
"$2" // replace with group 2

And there's a special zeroth group:

"$0" // replace with the entire match
like image 183
Bohemian Avatar answered Aug 06 '26 11:08

Bohemian


As the question was stated as why:

Referring to a captured group in your input, replacement strings can contain pieces of whatever you were matching:

replaceAll("some str(ing)", "another str$1");

will effectively replace "some" with "another". (Silly example, but to give you an idea of what it means.)

like image 25
akaIDIOT Avatar answered Aug 06 '26 09:08

akaIDIOT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!