【已解决】如何使用 dataview 插件过滤出某个二级标题下的内容

汇总【指定小标题下的全部内容】,包括task、普通文本等
2023-05-29更新:对代码做了完善,支持正则匹配,等等

```dataviewjs
const headers = ["文件名", "内容"];
// 目标小标题,支持正则匹配
const targetHeading = /^.{0,9}目标小标题(不含#).{0,4}$/i;
// 按【路径或文件夹、文件名、标签】筛选并按修改时间降序排列
const pages = dv.pages('!"00数据管理"').filter(p => !p.file.path.includes("龥") && /^(?!.*(排除的关键词2|模板\-)).*/.test(p.file.name)).sort(p=>p.file.mtime,"desc");
const pagesArray = pages.array();
const targetPagesArray = [];
const contentArray = [];

for(let i = 0; i < pagesArray.length;i++) {
    const currentFile = pagesArray[i].file;
    const sectionCache = app.metadataCache.getFileCache(currentFile);

    const headingCache = sectionCache.headings?.filter(h => {
        return targetHeading.test(h.heading)
    })

    if(headingCache?.length > 0) {
        const headingRange = {
            start: headingCache[0].position.start.offset,
            end: headingCache[0].position.end.offset,
        };
        const heading = headingCache[0].heading;
        const content = await dv.io.load(currentFile.path);

        if(!content) continue;
        const headingInRange = content.slice(headingRange.start, headingRange.end);
        const contentInNextRange = content.slice(headingRange.end);

        const level = headingInRange.match(/#{1,6}/)[0].length;
        const nextHeadingRegex = new RegExp(`(^|\\n)#{1,${level}}\\s`);

        const position = contentInNextRange.match(nextHeadingRegex);

        let contentRange;
        let positionEnd;

        if(position) {
            positionEnd = headingRange.end + position?.index;
            contentRange = content.slice(headingRange.end, positionEnd);
        }else {
            contentRange = content.slice(headingRange.end);
        }
        const link = dv.sectionLink(currentFile.name, heading)
        contentArray.push({
            file: link,
            content: contentRange,
        })
    }
    //将结果限制在50条以内
    if (contentArray.length >= 50) {
        break;
    }
}
dv.table(headers, contentArray.map(
    p =>
        [
            p.file,
            p.content,
        ]
))
5 个赞