Image

java.util.regex.Matcher.replaceFirst(replaceStr) - what kind of escaping is necessary?

I'm playing around with java.util.regex, and I just used the
Matcher.replaceFirst(String replacementStr) for my first time.

I'm trying to figure out what kind of escaping is necessary.

I was using as a replacementStr, a string that looked like this:

"c:\\src\\utils"

But the backslashes were lost in the replaced string.

The problem was fixed if I "double-double" escaped the backslashes like so:

"c:\\\\src\\\\utils"

I read in the API docs that the replacementString is evaluated for $signs, which it replaces with backreferences to the matched groups. But it says nothing about needing to escape the backslash. Why is it necessary?

You can see a sample testcase that demonstrates this here:

http://juke.cluttered.com/~ezust/local/src/sae/utils/VariableSubstitutor.java
http://juke.cluttered.com/~ezust/local/src/sae/utils/TestVariableSubstitutor.java