Last time, I had to create a quick fix in a rather ugly Java program. The functionality that had to be added was replacing the characters ‘||’ with the characters ‘|$|’.
So I made something like this:
myString = myString.replaceAll("||","|$|");
Now that was a quick fix, deploy it and move on…. NOT. The code I added just gave me this exception:
Exception in thread “main” java.lang.IllegalArgumentException: Illegal group reference
It appears that the replaceAll function is using regex to find and replace the Strings and the ‘|’ character has a special function in regex. Okay, so I’ll just escape the character:
myString = myString.replaceAll("\|\|","\|$\|");
Well, that is even worse. It is now complaining at compile time:
And I was in a big hurry….
So I decided to do the “||” replacement on the textfile, which was used as input, with a text editor, so I could at least move on.
And of course, lateron, just after a quick google, you’ll find that you just had to double escape the regex characters, like this, to make it work:
myString = myString.replaceAll("\\|\\|","\\|\\$\\|");
Although it does no good to the readiblity (and thus maintainability) of the code….