Escape Madness
11. Dezember 2008 - 23:15I 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:
C:\my\path
21 = 2
You need to escape the \ in the properties file, it should read:
my.path=C:\\my\\path
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:
"C:\\\\my\\\\path"
23 = 8
If you want to put that in a regular expression, you need to escape each \ with \\, which will lead to:
"C:\\\\\\\\my\\\\\\\\path"
24 = 16
This expression should be generated by another regular expression, so each \ needs to be replaced with \\, hence:
"C:\\\\\\\\\\\\\\\\my\\\\\\\\\\\\\\\\path"
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="" property="jboss.dir.escaped"> input="${$jboss.dir}" regexp="\\" replace="\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\" global="true"/> <replaceregexp br="" match="(?<=jboss.local.dir=).*$" replace="${jboss.dir.escaped}" flags="gm"> <!-- yadda, yadda, yadda --> </replaceregexp>
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.