Sunday, August 4, 2013

Escaping strings in Java or Groovy

Working with Strings in Java is a pain, because Java does its best to prevent you from using characters like " or \ in a string.

Escaping is a pain but there is no way around it - apart from ditching Java in favor of Groovy which is a lot more flexible.

Either you use apache commons library escapeJava(), or Groovy escapeUtils , or just write a little function:

def escapeString(theString) {
    return theString.replace('\\', '\\\\').replaceAll('"',"'").replaceAll('\n', '" +\n"')
    //this is the list of all replace you need to implement: {"'", "\\'"}, {"\"", "\\\""}, {"\\", "\\\\"},{"/", "\\/"}

and good luck.

No comments: