3

I just lost 1 hour to track what I consider not normal behaviour with replaceAll/replaceFirst in the String class.

If there is a backslash in the replacement String then they are removed when replacing. I then read that you can use Matcher.quoteReplacement(String) to create a proper replacement string,but my question is why? I can expect that the first argument should be escaped with Patter.quote(String) if you don't want the special meaning but I don't see a reason to change the replacement :(

Yes I will start using replace(CharSequence,CharSequence), just want to know why :)

Here is an example that clearly shows the "strange" behaviour:

public static void main(String[] args) {
    String out = "\\\\test\\\\";
    System.out.println(out);
    String result = "a".replaceAll("a", out);
    System.out.println(result);
}

note how second line is with only single backslashes as opposed to two like in the first line

2

2 Answers 2

2

Yes it is true that backslash needs to be doubly escaped as the first argument in String#replaceAll.

Reason:

It is due to the fact that your replacement String can contain back-references like $1, $2 etc even replacement text is also processed by underlying regex engine hence the need for double escaping same as the first argument, as you have also found out.

Sign up to request clarification or add additional context in comments.

Comments

2

As has been mentioned, the replacement string uses $ characters to reference capture groups.

Therefore, to insert a literal $, you need to escape it with a \.

You can see this in the source.

I'm not sure why they didn't use $$ like .Net does.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.