在 JavaScript 正则表达式中嵌入注释,就像在 Perl 中一样



有没有办法在JavaScript正则表达式中嵌入注释,就像在Perl中所做的那样? 我猜没有,但我的搜索没有找到任何说明你可以或不能的东西。

不能在正则表达式文本中嵌入注释。

您可以在传递给 RegExp 构造函数的字符串结构中插入注释:

var r = new RegExp(
    "\b"   + // word boundary
    "A="    + // A=
    "(\d+)"+ // what is captured : some digits
    "\b"     // word boundary again
, 'i');       // case insensitive

但是正则表达式文字要方便得多(请注意我是如何转义)我宁愿将正则表达式与注释分开:只需在您的正则表达式之前放置一些注释,而不是在里面。

编辑2018:这个问题和答案非常古老。EcmaScript 现在提供了处理此问题的新方法,更准确地说是模板字符串。

例如,我现在在节点中使用这个简单的实用程序:

module.exports = function(tmpl){
    let [, source, flags] = tmpl.raw.toString()
    .replace(/s*(//.*)?$s*/gm, "") // remove comments and spaces at both ends of lines
    .match(/^/?(.*?)(?:/(w+))?$/); // extracts source and flags
    return new RegExp(source, flags);
}

这让我可以做这样或这样或这样的事情:

const regex = rex`
    ^         // start of string
    [a-z]+    // some letters
    bla(d+)
    $         // end
    /ig`;
console.log(regex); // /^[a-z]+bla(d+)$/ig
console.log("Totobla58".match(regex)); // [ 'Totobla58' ]

现在有了严重的背痒,你可以做一些内联评论。请注意,在下面的示例中,对匹配的字符串中不会出现的内容进行了一些假设,尤其是关于空格。但我认为,如果你仔细编写process()函数,你经常可以做出这样的有意假设。如果没有,可能有创造性的方法来定义正则表达式的小"迷你语言扩展",使其工作。

function process() {
  var regex = new RegExp("\s*([^#]*?)\s*#.*$", "mg");
  var output = "";
  while ((result = regex.exec(arguments[0])) !== null ){
    output += result[1];
  }
  return output;
}
var a = new RegExp(process `
    ^f    # matches the first letter f
    .*   # matches stuff in the middle
    h    # matches the letter 'h'
`);
console.log(a);
console.log(a.test("fish"));
console.log(a.test("frog"));

这是一个代码笔。

另外,对于 OP,只是因为我觉得有必要这样说,这很整洁,但是如果您生成的代码与字符串连接一样冗长,或者如果您需要 6 个小时才能找出正确的正则表达式并且您是团队中唯一会费心使用它的人, 也许有更好的时间利用...

我希望你知道,我对你这么直言不讳,因为我珍惜我们的友谊。

最新更新