2

长期用户,第一次提问;对正则表达式非常陌生。我是一名设计师,试图让我在 InDesign 中的生活更轻松,所以如果这很简单,请耐心等待 :)

我正在编写一个脚本,该脚本将页面从主文件中提取到模板文件中。其中一些母版页具有在将最终文件导出为 PDF 进行打印时要使用的图层;当最终文件导出到电子邮件时,将使用其他层。因此,如果有人选中保存电子邮件的选项,我希望隐藏打印层并显示电子邮件层。很简单,但我想将代码简化为一个函数,这样我就可以将“print”或“email”指定为变量,然后脚本会将其与其中包含“print”的任何变量相匹配。正则表达式领域。

var openDocument = app.documents.item(0);
var LayerLength = openDocument.layers.length;

wordToMatch = "print";

for (i=0;i<LayerLength;i++)
{
    myRegEx = new RegExp(wordToMatch,"i");

    str = openDocument.layers.item(i).name;
    if (str.search(myRegEx) >= 0)
    {
        openDocument.layers.item(i).visible = true;
    }
}

所以,这确实有效。它做我想要它做的事情(还没有把它放在一个函数中,但我会到达那里)。它会找到其中带有“打印”的图层,然后使它们可见。

不过,这对我来说似乎并不理想。我认为定义一次正则表达式然后在 for 循环中多次使用它会更有意义,如下所示:

wordToMatch = "print";
myRegEx = new RegExp(wordToMatch,"i");

for (i=0;i<LayerLength;i++)
{
    str = openDocument.layers.item(i).name;

    if (str.search(myRegEx) >= 0)
    {
        openDocument.layers.item(i).visible = true;
    }
}

但这只能在第一层做它应该做的事情,然后它无法匹配任何后续层。

为什么是这样?我觉得我在这里误解了一些基本的东西,我想知道那是什么。

谢谢,布伦丹

4

1 回答 1

4

正则表达式具有 lastIndex 属性 - 当找到匹配项时,最后一个索引指向匹配后的下一个字符,只有在找到所有匹配项后才重置为 0。

这样您就可以在同一个字符串中找到下一个匹配项 - 因为您只是在寻找第一个匹配项,所以在循环中自己重置 lastIndex。

for(i= 0; i<LayerLength; i++){
    myRegEx.lastIndex= 0;
    str= openDocument.layers.item(i).name;
    if(str.search(myRegEx)>= 0){
        openDocument.layers.item(i).visible= true;
    }
}
于 2012-03-16T19:27:52.057 回答