Java and pattern matching

I had a very simple requirement. I had to escape certain characters in a string using a backslash.

Backslash is a very tricky character. Escaping involves preceding the character to be escaped with a backslash. Now, suppose you have a string which contains a backslash, and if you need to escape it, you need to enter 2 backslashes.

The complexity just begins. Backslashes have special meaning in regular expressions. Strings in Java also use backslash with a special meaning.

Combine all this and you reach hell.

I wanted to replace all occurrences of ” and with ” and respectively. Guess how I use Java for this?

	returnString = returnString.replaceAll("\", "\\");

	returnString = returnString.replaceAll(""","\"");

Yeah, that's how you do it!

Published by