为什么在不同情况下应使用不同数量的转义字符?

5
使用Java中的正则表达式时,为什么要使用"\n"来定义换行符,而使用"\\s"来定义空格字符?为什么反斜杠的数量不同?
3个回答

8
Java会对字符串进行解析,将其从您的代码转换为内部内存中的字符串,并在将字符串发送到正则表达式解析器之前进行处理。
Java将2个字符`\n`转换为换行符(ASCII代码0x0A),并将`\\s`中的前两个字符转换为单个反斜杠:`\s`。现在,这个字符串被发送到正则表达式解析器,由于正则表达式识别它们自己的特殊转义字符,因此将`\s`视为“任何空格”。
此时,代码`\n`已经存储为单个字符“换行符”,正则表达式不会再次处理它。
由于正则表达式也将集合`\n`识别为“换行符”,因此您还可以在Java字符串中使用`\\n` - Java将转义的`\\`转换为单个`\`,然后正则表达式模块找到`\n`,它(再次)被转换为换行符。

3

Java字符串有一定的允许转义序列集合,其中"\n"是其中之一,但"\s"不是。字符串无法理解正则表达式中空格的速记符号。您可能正在将Java字符串传递给RegExp构造函数,因此为了将"\s"作为字符串传递,您必须通过将其加倍来转义 "\"。


2
\在许多语言中都是特殊字符(在Java中,它在Stringchar中是特殊的),或者在正则表达式等工具中也是特殊的。在Stringchar中,它用于创建其他常规情况下无法编写的特殊字符。通过使用\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 asday[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",则会得到


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接