Escape Madness

I stumpled upon something funny at work today. It might help being a fellow programmer to consider this being funny. It took some time today to come up with a solution ...

Task: Change a path in a text file during a build process using the java build tool ant.

Solution: Use a Regular Expression to scan the text file and replace the value.

This is where the madness begins: You need to escape a backslash. Probably multiple times ...

20 = 1
The path contains one backslash:

21 = 2
You need to escape the \ in the properties file, it should read:

22 = 4
If you want to print the Path in a Java String (which ant more or less uses), you need to escape each \ with \\, that becomes:


23 = 8
If you want to put that in a regular expression, you need to escape each \ with \\, which will lead to:

24 = 16
This expression should be generated by another regular expression, so each \ needs to be replaced with \\, hence:

25 = 32
Put the thing into an build.xml file for ant, you you'll end up with 32 (thirty two!!!) backslashes to have one in the end. Without escaping 1 (one) backslash with 16 backslashes (written as 32, because each one of those 16 needs to be escaped), it won't work:

<propertyregex br="" 
    input="${$jboss.dir}" regexp="\\"
<replaceregexp br="" 
        <!-- yadda, yadda, yadda -->

Now that's efficiency. Thanks a lot, java folks.

Things like that never happen to me in perl. Oh dear perl, I really love you. For a reason.