Java 如何将转义字符写入字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4070577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write escape character to string?
提问by user488963
How to write escape character "\" to string?
如何将转义字符“\”写入字符串?
采纳答案by Powerlord
In a normal string, you use \\
在普通字符串中,您使用 \\
If this is in a regular expression, it needs to be \\\\
如果这是在正则表达式中,则需要 \\\\
The reason RegEx needs four is because both the String parser and RegEx engine support escapes. Therefore, \\\\
is parsed to \\
by the String parser then to a literal \
by the RegEx parser.
RegEx 需要四个的原因是字符串解析器和 RegEx 引擎都支持转义。因此,由 String 解析器\\\\
解析为\\
文本\
,然后由 RegEx 解析器解析为文字。
回答by Starkey
Escape the escape character: "\\"
转义转义字符: "\\"
回答by Bryan Denny
You escape certain characters by adding "\" in front of the character.
您可以通过在字符前添加“\”来转义某些字符。
So \\
will work for you.
所以\\
会为你工作。
回答by pyCoder
Use double \ in string
在字符串中使用双 \
String example = "C:\Program Files";
回答by Patrick
string = @"c:\inetpub\wwwroot\"
is the same as
是相同的
string = "c:\inetpub\wwwroot\"
in some cases... i'm not 100% sure but i think it might be language dependant... i KNOW "@" works in C#
在某些情况下……我不是 100% 确定,但我认为这可能取决于语言……我知道“@”在 C# 中有效
回答by codaddict
You can write:
你可以写:
String newstr = "\";
\
is a special character within a string used for escaping.
\
是字符串中用于转义的特殊字符。
"\"
does now work because it is escaping the second "
.
"\"
现在确实有效,因为它正在转义第二个"
.
To get a literal \
you need to escape it using \
.
要获得文字,\
您需要使用\
.