SyntaxError: nothing to repeat
JavaScript 异常“nothing to repeat”(或“regular expression 中量词无效”)发生于当正则表达式中的量词应用于空内容或应用于断言时。
消息
SyntaxError: Invalid regular expression: /\b+/: Nothing to repeat (V8-based) SyntaxError: Invalid regular expression: /(?=)+/u: Invalid quantifier (V8-based) SyntaxError: nothing to repeat (Firefox) SyntaxError: invalid quantifier in regular expression (Firefox) SyntaxError: Invalid regular expression: nothing to repeat (Safari)
错误类型
SyntaxError
哪里出错了?
量词用于指定字符或字符组在正则表达式中可以出现的次数。例如,a{3} 精确匹配字符 a 三次。因此,如果量词前面的内容不是可以匹配字符的东西,则该量词无效。例如:捕获组开头、或运算符的备选项开头等的量词不能重复任何内容。断言不消耗字符,因此重复它们也没有意义。
在非 Unicode 模式下,存在一种已弃用的语法,允许先行断言被量化。这是一种已弃用的语法,不应依赖它。
示例
无效案例
js
/\b+/; // \b is a word boundary assertion, it doesn't consume characters
/(*hello*)/;
有效情况
js
/b+/; // b is a character, it can be repeated
/(\*hello\*)/; // Escape the asterisks to match them literally