如何使用javascript在InDesign GREP find/change中将$2值存储到变量中

如何使用javascript在InDesign GREP find/change中将$2值存储到变量中,javascript,adobe-indesign,grep-indesign,Javascript,Adobe Indesign,Grep Indesign,我正在写InDesign javascript,它可以让GREP查找/更改-实际上现在我只需要找到一些文本,并将GREP在$2值中找到的内容保存到我的脚本变量中-我知道如何处理脚本的所有其他内容-所以我现在所需要的就是找到如何获得这$2 简单的例子: app.findGrepPreferences = NothingEnum.nothing; app.findGrepPreferences.findWhat = "(\\d)+(\\d)"; found = app.activeDocument.

我正在写InDesign javascript,它可以让GREP查找/更改-实际上现在我只需要找到一些文本,并将GREP在$2值中找到的内容保存到我的脚本变量中-我知道如何处理脚本的所有其他内容-所以我现在所需要的就是找到如何获得这$2

简单的例子:

app.findGrepPreferences = NothingEnum.nothing;
app.findGrepPreferences.findWhat = "(\\d)+(\\d)";
found = app.activeDocument.findGrep();
...
found[0].contents; // this store entire string with both digits and plus, and I need only $2 value (second digit in this case)

InDesign的JS接口不会为您这样做,它只会返回完全匹配的结果

由于
contents
是一个简单的Javascript字符串(不再是原生InDesign文本),因此可以使用Javascript自己的
match
函数:

..
app.findGrepPreferences.findWhat = "(\\d)+(\\d)";
found = app.activeDocument.findGrep();
m = found[0].contents.match (/(\d)+(\d)/);
alert (m.join('\n'));

注意不要将InDesign的GREP语法与Javascript的混合。特别是像
~这样的特殊字符,我知道这已经有了答案,但我想我应该提到另一种我认为有用的方法。一种方法是使用lookbehinds和lookaheads,这样第二组括号中的内容就是找到的字符串的全部。在您的情况下,您可以将搜索更改为

(?<=\\d)\\d(?!\\d)
(?
(\d+)(\d)
2014
201
4
(?<=\\d)\\d(?!\\d)