Nodejs 正则表达式错误:“无效的正则表达式:没有什么可重复的”

Nodejs regexp error: "Invalid regular expression: nothing to repeat"

本文关键字:正则表达式 什么 无效 Nodejs 错误      更新时间:2023-09-26

所以我有这个正则表达式:

(?:[ 't]*)?(?:'/'/|'/'*)[ 't]*#exclude[ 't]*([^'n*]*)[ 't]*(?:'*'/)?(?:[ 't]*['r'n]+)?((?:.|'n|'r)*?)(?:[ 't]*)?(?:'/'/|'/'*)[ 't]*#endexclude[ 't]*(?:'*'/)?(?:[ 't]*['r'n]+)?

它应该匹配看起来像这样的任何内容:

/* #exclude */
hurdur = somerandomtextorcode;
/* #endexclude */

我正在 https://regex101.com/(https://regex101.com/r/eA5oK9/1)等工具中尝试使用这种正则表达式,它只是简单地工作,没有错误。

但是,在nodejs环境中,我收到此错误,我真的不知道如何解决:

Warning: Invalid regular expression: /(?:[      ]*)?(?://|/*)[  ]*#exclude[
]*([^
]*)[    ]*(?:*/)?(?:[   ]*[
]+)?((?:.|
|
)?)(?:[         ]*)?(?://|/*)[  ]*#endexclude[  ]*(?:*/)?(?:[   ]*[
]+)?/: Nothing to repeat Use --force to continue.

任何这方面的帮助将不胜感激!

好吧,事实证明这是一个与我实际创建正则表达式的方式有关的问题。

我正在创建(并应用)像这样的正则表达式:

var rExclude = '(?:[ 't]*)?(?:'/'/|'/'*)[ 't]*#exclude[ 't]*([^'n*]*)[ 't]*(?:'*'/)?(?:[ 't]*['r'n]+)?((?:.|'n|'r)*?)(?:[ 't]*)?(?:'/'/|'/'*)[ 't]*#endexclude[ 't]*(?:'*'/)?(?:[ 't]*['r'n]+)?';
contents = contents.replace(new RegExp(rExclude, 'gi'), function () { return ""; });

这给了我开始文章中描述的错误。但是,由于正则表达式位于字符串中,JavaScript 决定以不同的方式处理正则表达式。您可以通过两种方式修复它:

解决方案 1此解决方案改变了字符串中内容转义的方式。

var rExclude = '(?:[ 't]*)?(?://|/''*)[ 't]*#exclude[ 't]*(?:''*/)?(?:.|'n|'r)*?(?://|/''*)[ 't]*#endexclude[ 't]*(?:''*/)?';
contents = contents.replace(new RegExp(rExclude, 'gi'), function () { return ""; });

解决方案 2此解决方案改变了实际正则表达式的创建方式:

contents = contents.replace(/(?:[ 't]*)?(?:'/'/|'/'*)[ 't]*#exclude[ 't]*(?:'*'/)?(?:.|'n|'r)*?(?:'/'/|'/'*)[ 't]*#endexclude[ 't]*(?:'*'/)?/gi, function () { return ""; });

不幸的是,这只是另一个奇怪的JavaScript怪癖。

双倍

的反斜杠。

注意这里:(?:*/)?没有反斜杠?这意味着您的*正在尝试重复。无。没什么可重复的。