regex - 将Markdown链接从内联转换为引用

标签 regex markdown sublimetext3 sublimetext

我有一个使用Github's markdown格式化的changelog文件。

最初,我将内联链接用于需要添加的每个链接,即:

This is some [example](http://www.stackoverflow.com) line of text.

随着时间的流逝,随着文件大小的增加,主要由于这种插入链接的方式使文件变得有些困惑。

我想将所有链接从内联转换为引用(请参阅description of each),即将上面的行转换为此:
This is some [example][1] line of text.

[1]: http://www.stackoverflow.com

由于该文件很大,并且包含许多内联链接,所以我想知道是否存在一些自动方法来执行此操作。我使用Sublime Text 3进行编辑,但找不到适合此任务的软件包。也许一些聪明的正则表达式?

最佳答案

这是一个很大的要求!

我刚刚创建了一个新的Node.js程序(我知道它不是GUI,但似乎更多的人希望此功能)在GitHub上执行此操作。

这也是代码:

// node main.js test.md result.md

var fs = require('fs')
fs.readFile(process.argv[2], 'utf8', function (err, markdown) {
    if (err) {
        return console.log(err);
    }
    var counter = 1;
    var matches = {};
    var matcher = /\[.*?\]\((.*?)\)/g;
    while (match = matcher.exec(markdown)) {
        if (!matches[match[1]]) matches[match[1]] = counter++;
    }
    console.log(matches);
    Object.keys(matches).forEach(function(url) {
        var r = new RegExp("(\\[.*?\\])\\(" + url + "\\)", "g");
        markdown = markdown.replace(r, "$1[" + matches[url] + "]");
        markdown += "\n[" + matches[url] + "]: " + url;
    });

    fs.writeFile(process.argv[3], markdown, 'utf8', function (err) {
        if (err) return console.log(err);
    });

});

关于regex - 将Markdown链接从内联转换为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30917399/

相关文章:

jupyter-notebook - Google Colab 中的编号标题和目录

editor - Sublime 的 : How to select by single word in CamelCase variable?

ruby-on-rails - Ubuntu 终端 : I can't seem to launch programs from my terminal anymore. 我使用 sublime、rails 和 heroku

javascript - 如何删除所有非字母字符,javascript

regex - 使用python正则表达式转义无效的 Markdown

ruby - 当我要求它匹配数字时,为什么扫描匹配 ""个字符?

sublimetext3 - sublime text 3 "window tab"切换键盘快捷键

regex - 如何从正则表达式子模式中排除一组替代方案?

reactjs - 从路径显示 Markdown 文件与 typescript react

r - 如何在 Rmd 报告中指定 toc 将在哪个级别展开?