"\n"
来定义换行符,而使用"\\s"
来定义空格字符?为什么反斜杠的数量不同?Java字符串有一定的允许转义序列集合,其中"\n"是其中之一,但"\s"不是。字符串无法理解正则表达式中空格的速记符号。您可能正在将Java字符串传递给RegExp
构造函数,因此为了将"\s"作为字符串传递,您必须通过将其加倍来转义 "\"。
\
在许多语言中都是特殊字符(在Java中,它在String
或char
中是特殊的),或者在正则表达式等工具中也是特殊的。在String
或char
中,它用于创建其他常规情况下无法编写的特殊字符。通过使用\x
,其中x
是该特殊字符的表示形式,您可以创建以下内容:
\t
制表符\b
退格键\n
换行符\r
回车键\f
进纸键\'
single quote ('
is special in char
because it represents where char starts and ends, so to actually write '
character you need to escape it and write it as
here we start creating character
| here we end creating character
↓ ↓
'\''
↑↑
here we created literal of '
\"
double quote - similarly to \'
in char
, in String "
represents where it starts and ends, so to put "
literal into string (to actually be able to write it) you need to escape it
here we start creating String
| here we end creating String
↓ ↓
"\""
↑↑
here we created literal of "
\\
backslash - since \
is special character used to create others special character there has to be a way to un-special it so we could actually print \
as simple literal.
Problem: how to write string representing day\night
? If you write it such string in a way "day\night" it will be interpreted as
day[newline]ight`.
So in many languages to represent \
literal another \
is added before it to escape it. So String which represent day\night
needs to be written as "day\\night"
(now \
in \n
is escaped so it no longer represents \n
- newline - but concatenation of \
and n
characters)
如果要表示接受任何空格的字符类的正则表达式,您需要实际传递\s
。
但是表示\s
的字符串需要编写为"\\s"
,因为如前所述,在字符串中\
是特殊的,需要转义。
如果将\s
编写为"\s"
,则会得到