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 http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html apache commons library escapeJava(), or Groovy escapeUtils http://groovy.codehaus.org/gapi/groovy/json/StringEscapeUtils.html , 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: