You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何正则无法捕获ng-repeat的track by表达式?如何修复?

解决AngularJS ng-repeat表达式正则匹配中track by子句捕获失败的问题

你尝试用正则解析AngularJS的ng-repeat表达式,提取变量、集合和可选的track by表达式,但发现带track by的表达式中,trackingExpression始终为undefined。

问题原因

你的正则里第二个捕获组用了贪婪模式的.+,它会匹配从in之后到字符串末尾的所有内容——包括track by ...部分。因为贪婪匹配会尽可能多地消耗字符,导致后面可选的(?:\s+track\s+by\s+(.+))?分支完全没有匹配机会,所以第三个捕获组始终返回undefined。

解决方法

把第二个捕获组的贪婪匹配改成非贪婪模式,让它匹配到track by出现前的内容就停止,只需要把第二个.+改成.+?:

修改后的正则:

const regex = /\s*(.+)\s+in\s+(.+?)(?:\s+track\s+by\s+(.+))?/;

如果要更严谨,也可以用否定前瞻确保第二个捕获组不包含track by:

const regex = /\s*(.+)\s+in\s+((?:(?!track\s+by).)+)(?:\s+track\s+by\s+(.+))?/;

测试验证

运行修改后的代码:

const ngRepeatExpressions = [
  'key, value in items track by key',
  'item in items',
  'item in items track by item.id',
];
const regex = /\s*(.+)\s+in\s+(.+?)(?:\s+track\s+by\s+(.+))?/;
ngRepeatExpressions.forEach((expression) => {
  const [, variables, collection, trackingExpression] = expression.match(regex);
  console.log({variables, collection, trackingExpression});
});

输出结果完全符合预期:

{ variables: 'key, value', collection: 'items', trackingExpression: 'key' }
{ variables: 'item', collection: 'items', trackingExpression: undefined }
{ variables: 'item', collection: 'items', trackingExpression: 'item.id' }

内容的提问来源于stack exchange,提问作者Jon Sud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:00:41