假设我们需要从pug
模板中获取包含文件的所有路径。
例如我们需要从layouts/BasicLayout
和TopPage/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'
}
});
我不喜欢我需要使用相同的正则表达式搜索两次。 我该怎么做才能美化上述解决方案?