英文:
Java: Purpose of double \\ characters?
问题
command = command.replaceAll("\\{player}", e.getPlayer().getName());
What is the purpose of the "\\" in "\\{player}" within that line?
Why doesn't the programmer just do "{player}"?
英文:
command = command.replaceAll("\\{player}", e.getPlayer().getName());
What is the purpose of the "\" in "\\{player}" within that line?
Why doesn't the programmer just do "{player}" ?
答案1
得分: 6
这是一个转义序列。因为在正则表达式中,{
字符有特殊含义,所以需要进行转义,以表示你实际上是指字面的 {
。
英文:
That's an escape sequence. Since the {
character has a special meaning in a regex, it needs to be escaped to signify you actually meant the literal {
.
答案2
得分: 2
反斜杠通常用于“转义”字符。通常可以用于正则表达式的字符。在这种情况下,{} 可以被解释为正则表达式(您可以用它进行字符串操作),因此您必须转义它们,以便您的 {} 被解释为文字括号,而不是正则表达式。
英文:
Backslash are usually to "escape" characters. Characters that usually can be used for regex. In this case, the {} can be interpreted as regex (which you can utilize for string manipulations), hence why you'd have to escape them for your {} to be interpreted as a literal brackets instead of reg ex.
答案3
得分: 1
\后面的一些字符具有特殊含义。
例如,\n 换行 \t 输入"tab"字符,诸如此类。
因此,如果您确实想在代码中写入\,比如 "c:\someFolder\someFile"
,您应该使用 "C:\\someFolder\\someFile"
</br>
\ 被称为转义字符
如果您写成
String text = "firstname\lastname";
编译器会给出"非法转义字符"的错误
这意味着您不应该单独使用""在您的代码中。
祝编码愉快!
英文:
"\ with some other characters have special meanings.
For example, \n moves to next line \t writes "tab" character and so on.
Because of this, if you really want to write \ in your code like, "c:\someFolder\someFile"
you should use "C:\\someFolder\\someFile"
</br>
\ called escape character
If you write
String text ="firstname\lastname";
compiler gives you an error "illegal escape character"
It means that you should not use"" alone in your code.
Happy coding!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论