Java用'(撇号/单引号)和\(反斜杠)替换问题 [英] Java replace issues with ' (apostrophe/single quote) and \ (backslash) together
问题描述
'
更改为 \'
。 这是一个示例代码:
这是'it'.replace(' \');
此输出仍然是:
这是'它'。
它认为我只是为了引用一个转义字符。
所以我尝试了这两个代码:
这是'it'.replace( ',\\); // \\为反斜杠,而'char
'这是'it'.replace(',\\\); // \\为反斜杠,\'为'char
以上STILL产生相同的输出:
这是'it'
/ pre>
我只能看到这样才能真正吐出一个斜线:
这是'it'.replace(',\\\\\);
其结果如下:
这是\\'它
任何建议?我只想用
\'
替换'
。
这似乎不应该是那么困难。
解决方案首先,如果你试图编码针对查询字符串的apostophes,它们需要为URLEncoded,不会以前导反斜杠进行转义。为此使用
URLEncoder.encode(String,String)
(BTW:第二个参数应该始终为UTF-8
)。其次,如果要使用反斜线撇号替换所有实例的脚本,则必须使用前导反斜杠来转义字符串表达式中的反斜杠。像这样:这是'it'.replace(',\\\
编辑:
您可能正在尝试动态构建SQL语句。 不要这样做。您的代码将易受SQL注入攻击。而是使用
PreparedStatement
。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.
解决方案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
.这篇关于Java用'(撇号/单引号)和\(反斜杠)替换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!