tags:

views:

814

answers:

4

Hello,
I have this string: "\"Blah \'Blah\' Blah\"". There is another string inside it. How do I convert that into: Blah 'Blah' Blah? (you see, unescaping the string.) This is because I get a SQL Where query:

WHERE blah="Blah \'Blah\' Blah"

When I parse this, I get the string above (still inside quotes and escaped.) How would I extract that, un-escaping the string? Or is ther some much easier way to do this? Thanks,
Isaac

A: 
"\"Blah \'Blah\' Blah\"".replaceAll("\"", "")
dfa
If the string was "\"Blah \\"Blah\\" Blah\"", it would come out wrong: Blah \Blah\ Blah.
Isaac Waller
A: 

Put the string in a property file, Java supports XML property files and the quote character does not need to be escaped in XML.

Use loadFromXML(InputStream in) method of the Properties class.

You can then use the MessageFormat class to interpolate values into the String if needed.

BeWarned
A: 

This should be about right. This assumes that if it starts with a quote, it ends with a quote.

if (val.startsWith("\"") || val.startsWith("\'")) 
   val = val.substring(1, val.length-2);

You may wish to add val = val.trim(); as well.

altCognito
+15  A: 

DO NOT DO THIS.

Follow the proper steps for parametrization of a query on your Database/Platform, and you won't have to escape anything. You also will protect yourself from injection vulnerabilities.

FlySwat
+1, but how will I hack the site. ;(
altCognito
No, you see, I am not the one who creates the SQL query, it is my job to parse it. I have a SQL interface to a web service, and I have the parametrization part done, but for those people who don't like that, and do it the bad way, I have to support it. I guess I could just throw a exception, but I would like to fully support it.
Isaac Waller
Then your web service interface is broken. It should take the query and the queries parameters as separate items.
FlySwat
It does! That is the preferred way! But, to fully support SQL, I must support the strings directly in the query. It is bad, I agree, but I must.
Isaac Waller
Or, I might just throw a exception when somebody tries to do it that way...
Isaac Waller
I'd do that. Force the consumers to use your service properly.
FlySwat
I'd have to agree with this answer and encourage you to reject the request.
Software Monkey
If you need to parse SQL, create a "real" parser and lexer, decoding the string one character at a time, into tokens and then create a syntax tree.
robinr