从 Chrome 控制台,我注意到了这个奇怪的地方:
/[^A-z]/.test("^")
false
/[A-z]/.test("^")
true
"^".charCodeAt(0)
94
"A".charCodeAt(0)
65
"z".charCodeAt(0)
122
/[a-zA-Z]/.test("^")
false
插入符号在65-122范围内匹配是有意义的,因为它的字符代码是94,但我没有意识到/[A-z]/不等于/[a-zA-Z]/。
所以我想我的问题是,javascript 是否使用 ASCII 代码来进行 A-z 等范围匹配?这就是这种行为的解释吗?
编辑:
经过进一步调查,这似乎是真的
String.fromCharCode(91)
"["
String.fromCharCode(92)
"\"
String.fromCharCode(93)
"]"
String.fromCharCode(94)
"^"
String.fromCharCode(95)
"_"
String.fromCharCode(96)
"`"
/[^A-z]/.test("^[\\_`")
false
最佳答案
ECMAScript 15.10.2.15在正则表达式求值期间处理基于范围的字符集的生成。当构建从字符 A
到字符 B
的范围(即 A-B
)时:
- Let a be the one character in CharSet A.
- Let b be the one character in CharSet B.
- Let i be the code unit value of character a.
- Let j be the code unit value of character b.
- If i > j then throw a SyntaxError exception.
- Return the set containing all characters numbered i through j, inclusive.
这里的短语“代码单元值”is a Unicode term 。因此,A-z
范围包括 Unicode 代码单元值落在 A
和 z
代码单元值(含)之间的所有字符。此范围 (0x41
- 0x7A
) 确实包括 six non-alphabetic characters :
U+005B [ 5b LEFT SQUARE BRACKET
U+005C \ 5c REVERSE SOLIDUS
U+005D ] 5d RIGHT SQUARE BRACKET
U+005E ^ 5e CIRCUMFLEX ACCENT
U+005F _ 5f LOW LINE
U+0060 ` 60 GRAVE ACCENT
关于Javascript 正则表达式字符范围 A-z 匹配插入符 ("^"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19546760/