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

如何用JavaScript正则表达式替换文件中的YAML前置元数据?

替换YAML前置元数据的正则表达式方案

针对你要替换文件中YAML前置元数据的需求,可使用以下正则表达式实现:

/^---\n([\s\S]*?)\n---/

正则规则说明:

  • ^---\n:精准匹配文件开头的---标记及紧随的换行符,确保只定位文件最顶部的YAML块
  • ([\s\S]*?):以非贪婪模式匹配任意字符(含换行),避免过度匹配到文件后续内容
  • \n---:匹配YAML块结尾的换行符和---闭合标记

完整代码示例:

templateFile = templateFile.replace(/^---\n([\s\S]*?)\n---/, YAML.stringify(frontmatter))

兼容场景调整:

如果需要兼容YAML块结尾带空格的情况(比如--- ),可将正则调整为:

/^---\n([\s\S]*?)\n---\s*/

如果文件原本没有YAML前置元数据,可补充判断逻辑实现新增:

const yamlRegex = /^---\n([\s\S]*?)\n---/;
let updatedContent;
if (yamlRegex.test(templateFile)) {
  updatedContent = templateFile.replace(yamlRegex, YAML.stringify(frontmatter));
} else {
  // 在文件开头插入新的YAML前置元数据
  updatedContent = `${YAML.stringify(frontmatter)}\n${templateFile}`;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 18:22:02