从多个匹配项中获取所有捕获组时,避免使用相同的正则表达式进行双重搜索

时间:2018-12-04 07:13:17

标签: javascript regex typescript regex-group

假设我们需要从pug模板中获取包含文件的所有路径。 例如我们需要从layouts/BasicLayoutTopPage/HeroImage中获取 下面的模板:

extends layouts/BasicLayout

block append PageContent
  include TopPage/HeroImage

我通过这种方式解决了这个问题:

/** example:[ 'extends layouts/BasicLayout\r\n\r', '\n  include TopPage/HeroImage' ] */
let rowsContainsIncludeFileExpression: RegExpMatchArray | null = currentFileContent.match(includesResolutionRule);

if (!rowsContainsIncludeFileExpression) {
  // strict null check for TypeScript
  throw new Error();
}

rowsContainsIncludeFileExpression.forEach( (rowContainsIncludeExpression: string) => {

  /**
   * For 'extends layouts/BasicLayout\r\n\r' results will be:
   *    [ 'extends layouts/BasicLayout\r\n\r',
   *      'layouts/BasicLayout', // <- desired result
   *      index: 0,
   *      input: 'extends layouts/BasicLayout\r\n\r' ]
   */

  let matches: RegExpMatchArray | null = includesResolutionRule.exec(rowContainsIncludeExpression);
  if (matches) {
    let pathToFileRelativeToParentFileDirectory: string = matches[1]; // 'layouts/BasicLayout'
  }
});

我不喜欢我需要使用相同的正则表达式搜索两次。 我该怎么做才能美化上述解决方案?

0 个答案:

没有答案