为什么我在不同情况下使用不同数量的转义字符? [英] Why should I use a different number of escape characters in different situations?

查看:147
本文介绍了为什么我在不同情况下使用不同数量的转义字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java中的正则表达式,为什么我应该编写\ n来定义换行符和\\\\ 来定义空格字符?

With regular expressions in Java, why I should write "\n" to define a new line character and "\\s" to define whitespace character?

为什么反斜杠的数量不同?

Why does the quantity of backslashes differs?

推荐答案

Java自己进行字符串解析,将其从代码转换为内存中的内部字符串,然后将字符串发送到正则表达式解析器。

Java does its own string parsing, converting it from your code to an internal string in memory and before it sends the string to the regex parser.

Java将2个字符 \ n 转换为换行符(ASCII码 0x0A )和 \\\\ 中的前两个(!)字符到一个反斜杠: \s 。现在这个字符串被发送到正则表达式解析器,并且由于正则表达式识别他们的自己的特殊转义字符,它会处理 \ s asany whitespace。

Java converts the 2 characters \n to a linefeed (ASCII code 0x0A) and the first 2 (!) characters in \\s to a single backslash: \s. Now this string is sent to the regex parser, and since regular expressions recognize their own special escaped characters, it treats the \s as "any whitespace".

此时,代码 \ n 已经存储作为单个字符linefeed,正则表达式不再处理它。

At this point, the code \n is already stored as a single character "linefeed", and the regular expression does not process it again.

因为正则表达式识别集合 \ n 作为换行,您也可以在Java字符串中使用 \\ n - Java转换为将 \\ 转义为单个 \ ,然后正则表达式模块找到 \ n ,(再次)被翻译成换行符。

Since regular expressions also recognize the set \n as "a linefeed", you can also use \\n in your Java string -- Java converts the escaped \\ to a single \, and the regular expression module then finds \n, which (again) gets translated into a linefeed.

这篇关于为什么我在不同情况下使用不同数量的转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆