Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

I seem to be having issues. I have a query string that has values that can contain single quotes. This will break the query string. So I was trying to do a replace to change ' to \'.

Here is a sample code:

"This is' it".replace("'", "\'"); 

The output for this is still:

"This is' it". 

It thinks I am just doing an escape character for the quote.

So I tried these two pieces of code:

"This is' it".replace("'", "\\'");  // \\ for the backslash, and a ' char "This is' it".replace("'", "\\\'"); // \\ for the backslash, and \' for the ' char 

Both of the above STILL results in the same output:

"This is' it" 

I can only seem to get this to actually spit out a slash with:

"This is' it".replace("'", "\\\\'"); 

Which results in:

"This is\\' it" 

Any suggestions? I just want to replace a ' with \'.

It doesn't seem like it should be that difficult.

like image 788
derekmw Avatar asked Jun 06 '11 21:06

derekmw


People also ask

How do I change the apostrophe in Java?

replaceAll("\\'", "\\\\'");

How do you replace a single quote with a string?

Use the String. replace() method to replace double with single quotes, e.g. const replaced = str. replace(/"/g, "'"); . The replace method will return a new string where all occurrences of double quotes are replaced with single quotes.

How do you escape an apostrophe in a string in Java?

Use escapeEcmaScript method from Apache Commons Lang package: Escapes any values it finds into their EcmaScript String form. Deals correctly with quotes and control-chars (tab, backslash, cr, ff, etc.). So a tab becomes the characters '\\' and 't' .

How do you replace a double quote in a string in Java?

String details = "Hello \"world\"!"; details = details. replace("\"","\\\""); System. out. println(details); // Hello \"world\"!


2 Answers

First of all, if you are trying to encode apostophes for querystrings, they need to be URLEncoded, not escaped with a leading backslash. For that use URLEncoder.encode(String, String) (BTW: the second argument should always be "UTF-8"). Secondly, if you want to replace all instances of apostophe with backslash apostrophe, you must escape the backslash in your string expression with a leading backslash. Like this:

"This is' it".replace("'", "\\'"); 

Edit:

I see now that you are probably trying to dynamically build a SQL statement. Do not do it this way. Your code will be susceptible to SQL injection attacks. Instead use a PreparedStatement.

like image 158
Asaph Avatar answered Sep 18 '22 11:09

Asaph


Use "This is' it".replace("'", "\\'")

like image 35
Marcelo Avatar answered Sep 20 '22 11:09

Marcelo