什么是\? (反斜线问号)转义序列是什么意思? [英] What does the \? (backslash question mark) escape sequence mean?
问题描述
转义序列 \w
是非法并发出警告,因此正则表达式 / \w /
必须写为 @\\w
;转义序列 \?
是有效,显然是并且不会发出警告,因此正则表达式 / \?/
必须写为 @ \\?
(即反斜杠必须被转义)
问号不像 \t
或 \\\
,所以为什么
\?
有效转义序列?
编辑:为了澄清,我不是问量词,我在问一个字符串转义序列。也就是说,这不会发出警告:
NSString * valid = @\?
相比之下,这个发出警告(未知转义序列 \w'):
NSString * invalid = @\w;
它指定一个文字问号。这是需要的,因为一个鲜为人知的功能,称为 trigraphs ,您可以在其中写一个三个字符序列从问号开始替换另一个字符。如果您启用了三位图,为了写??在一个字符串中,您需要将其写为?\?
,以防止预处理程序尝试将其作为三字母的开头读取。
(如果你想知道为什么有人会介绍这样的功能?:某些键盘或字符集不包括常用的符号,如 {
,所以他们介绍了三字母,所以你可以写 ??<
。)
I'm writing a regular expression in Objective-C.
The escape sequence \w
is illegal and emits a warning, so the regular expression /\w/
must be written as @"\\w"
; the escape sequence \?
is valid, apparently, and doesn't emit a warning, so the regular expression /\?/
must be written as @"\\?"
(i.e., the backslash must be escaped).
Question marks aren't invisible like \t
or \n
, so why is \?
a valid escape sequence?
Edit: To clarify, I'm not asking about the quantifier, I'm asking about a string escape sequence. That is, this doesn't emit a warning:
NSString *valid = @"\?";
By contrast, this does emit a warning ("Unknown escape sequence '\w'"):
NSString *invalid = @"\w";
It specifies a literal question mark. It is needed because of a little-known feature called trigraphs, where you can write a three-character sequence starting with question marks to substitute another character. If you have trigraphs enabled, in order to write "??" in a string, you need to write it as "?\?"
in order to prevent the preprocessor from trying to read it as the beginning of a trigraph.
(If you're wondering "Why would anybody introduce a feature like this?": Some keyboards or character sets didn't include commonly used symbols like {
. so they introduced trigraphs so you could write ??<
instead.)
这篇关于什么是\? (反斜线问号)转义序列是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!