简体   繁体   English

Java字符串用“ \\”替换

[英]Java String replace “ with \”

I have to replace " with \\" in java , I tried 我必须在java中用“替换为\\”,

String.replaceall("\\"","\\\\\\"") String.replaceall(“ \\”“,” \\\\\\“”)

but it dint work 但它的工作

Thanks in advance 提前致谢

Assuming you want a literal \\ then you need to escape it in your regular expression (the tricky part is that \\ is itself the escape character). 假设您要使用文字\\则需要在正则表达式中对其进行转义(棘手的部分是\\本身是转义字符)。 You can do something like, 你可以做类似的事情,

String msg = "\"Hello\"";
System.out.println(msg);
msg = msg.replaceAll("\"", "\\\\\"");
System.out.println(msg);

Output (indicating the changing " s) is 输出(指示变化的" )为

"Hello"
\"Hello\"

According to the javadoc, replaceAll does regular expression matching. 根据javadoc, replaceAll 正则表达式匹配。 That means that the first parameter is treated as a regular expression, and the second parameter also has some characters with special meanings. 这意味着第一个参数被视为正则表达式,第二个参数也具有一些具有特殊含义的字符。 See the javadoc . 参见javadoc

The " character isn't special in regular expressions, so you don't need to do anything with it. But for the replacement expression, the backslash is special. If you have a replacement string and you don't want any of the characters to be treated as special, the easiest way is to use Matcher.quoteReplacement : "字符在正则表达式中不是特殊的,因此您无需对其进行任何操作。但是对于替换表达式,反斜杠是特殊的。如果您有替换字符串并且不希望使用任何字符,被视为特殊,最简单的方法是使用Matcher.quoteReplacement

s.replaceAll("\"",Matcher.quoteReplacement("\\\""))

Also note that this doesn't modify s at all. 还要注意的是,这并不改变s的。 replaceAll returns a string and you have to assign it to something (perhaps s , perhaps something else). replaceAll 返回一个字符串,您必须将其分配给某些内容(也许是s ,也许还有其他内容)。 (I don't know whether you were making that mistake or not, but it's a very common one on StackOverflow.) (我不知道您是否犯了这个错误,但这在StackOverflow上是很常见的错误。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM