gpt4 book ai didi

javascript - 正则表达式中字符类中的小数转义

转载 作者:行者123 更新时间:2023-12-03 04:55:34 24 4
gpt4 key购买 nike

有人可以根据 ECMAScript 标准解释字符类中十进制转义的语义吗?

例如,以下模式意味着什么?它应该抛出语法错误吗?

[\11]

以下是核心规范的相关部分:

  • 21.2.2.19 ClassEscape

    The production ClassEscape::DecimalEscape evaluates as follows:

    1. Evaluate DecimalEscape to obtain an EscapeValue E.
    2. If E is not a character, throw a SyntaxError exception.
    3. Let ch be E's character.
    4. Return the one-element CharSet containing the character ch.
  • 21.2.2.11 DecimalEscape

    The production DecimalEscape::DecimalIntegerLiteral evaluates as follows:

    1. Let i be the MV of DecimalIntegerLiteral.
    2. If i is zero, return the EscapeValue consisting of the character U+0000 (NULL).
    3. Return the EscapeValue consisting of the integer i.

    The definition of “the MV of DecimalIntegerLiteral” is in 11.8.3.

    • NOTE
      If \ is followed by a decimal number n whose first digit is not 0, then the escape sequence is considered to be a backreference. It is an error if n is greater than the total number of left capturing parentheses in the entire regular expression. \0 represents the character and cannot be followed by a decimal digit.

网络浏览器的附加功能中还提到了 ClassEscape:

  • B.1.4.1 Pattern Semantics

    ClassEscape (21.2.2.19) includes the following additional evaluation rules:

    The production ClassEscape::DecimalEscapebut only if … evaluates as follows:

    1. Evaluate DecimalEscape to obtain an EscapeValue E.
    2. Assert: E is a character.
    3. Let ch be E's character.
    4. Return the one-element CharSet containing the character ch.

我的主要问题是,我觉得规则 DecimalEscape 仅在识别 0 时才生成字符(然后返回 U+0000 ),否则它返回一个整数,但在 Firefox 中使用 Javascript 控制台测试时我无法得到语法错误。

以下是我发现的一些结果:

// This is the only one I understand:
/[\0]/.test("\x00") // true

// Now it gets strange
/[\1]/.test("\x01") // true
/[\2]/.test("\x02") // true
/[\3]/.test("\x03") // true
/[\4]/.test("\x04") // true
/[\5]/.test("\x05") // true
/[\6]/.test("\x06") // true
/[\7]/.test("\x07") // true
/[\8]/.test("\x08") // false
/[\9]/.test("\x09") // false
/[\10]/.test("\x0a") // false
/[\11]/.test("\x0b") // false

// This is not interpreted as `\1` and `0`
/[\10]/.test("0") // false

// Also, it's not a backreference
/((((((((((a))))))))))[\10]/.test("aa") // false

为什么它返回 true 直到 7,然后返回 false ?这不应该与八进制有关。我希望得到一些澄清。

最佳答案

/[\0]/.test("\x00")
...
/[\7]/.test("\x07")

返回true,因为转义整数被视为八进制表示法(基数8)中的数字。

显然,当您使用基数 8 中未使用的 8 和 9 时,就不再可能了。在这种情况下,反斜杠将被忽略。

/[\10]/.test("\x0a")
/[\11]/.test("\x0b")

返回false,因为\10(基数8)给出8(基数10)

/[\10]/.test("\x08")
/[\11]/.test("\x09")

将返回true

此行为是浏览器附加功能(兼容性)的一部分。该部分B.1.2 String Literals添加LegacyOctalEscapeSequenceEscapeSequence 的产生规则。此规则定义了从 0 到 255 的代码单元的八进制转义符 \0\377

关于javascript - 正则表达式中字符类中的小数转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42447541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com