如何打印反斜杠?

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

How do I print a back slash?

问题

当我尝试使用System.out.println("\\\\");时,它会打印出两个反斜杠,我只想打印一个。

英文:

When I try System.out.println("\\\\");, it prints two back slashes, I only want to print one.

答案1

得分: 4

System.out.println("\\\"");. 反斜杠是‘转义’字符:您写一个反斜杠,然后再写一个其他字符,两者共同表示一个单个字符(字符串长度为1);这是一种通常难以正常书写的字符。

"\n" 长度为1,是换行字符。

"\\\"" 长度为1,是一个单独的反斜杠。

英文:

System.out.println("\\");. Backslash is the 'escape' character: you write one backslash, and then one other character which together represents a single character (the string length would be 1); a character that is hard to write normally.

"\n" has length 1 and is a newline character.

"\\" has length 1 and is one single backslash.

答案2

得分: 2

只是为了完整地呈现情景。在Java正则表达式/Pattern中,当您想匹配文字反斜杠时,使用"\\\\"。您需要为正则表达式转义一次,然后两个反斜杠都需要再次转义...因为它是一个字符串文字。

简而言之:

  • "\\" 用于字符串文字中的文字反斜杠
  • "\\\\" 用于在字符串文字中表示的正则表达式中匹配文字反斜杠

(如果您仔细考虑,这一切都是有道理的。)

英文:

Just to complete the picture. You use "\\\\" when you want to match a literal backslash in a Java regex / Pattern. You need to escape once for the regex, and then both backslashes need to be escaped again ... because it is a String literal.

In short:

  • "\\" for a literal backslash in a string literal
  • "\\\\" to match a literal backslash in a regex expressed as a string literal

(It all makes sense if you think about it carefully.)

答案3

得分: 0

只需执行:

\\

示例可在此处查看:

System.out.println("\\");

生成:

\
英文:

Just do:

\\

Example can be seen here:

System.out.println("\\");

Which produces:

\

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

发表评论

匿名网友

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

确定