Java: 双斜杠(\\)字符的用途是什么?

huangapple go评论174阅读模式
英文:

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"字符,诸如此类。
因此,如果您确实想在代码中写入\,比如 &quot;c:\someFolder\someFile&quot;,您应该使用 &quot;C:\\someFolder\\someFile&quot; </br>
\ 被称为转义字符
如果您写成

String text = &quot;firstname\lastname&quot;;

编译器会给出"非法转义字符"的错误
这意味着您不应该单独使用"&quot;在您的代码中。
祝编码愉快!

英文:

"\ 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, &quot;c:\someFolder\someFile&quot; you should use &quot;C:\\someFolder\\someFile&quot; </br>
\ called escape character
If you write

String text =&quot;firstname\lastname&quot;;

compiler gives you an error "illegal escape character"
It means that you should not use"&quot; alone in your code.
Happy coding!

huangapple
  • 本文由 发表于 2020年4月10日 07:50:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/61132032.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定