正则表达式匹配Markdown链接

19

我有一个包含Markdown格式的字符串。我正在尝试使用正则表达式去除所有的Markdown,但是在匹配链接时遇到了麻烦。这是我目前的进展:

function stripMarkdown(text) {
  var str = String(text).replace(/(__|\*|\#)/gm, '');
  return str;
}

var testStr = '# This is the title. ## This is the subtitle. **some text** __some more text__. [link here](http://google.com)'

stripMarkdown(testStr);

所以我相信上面的内容会去掉除链接之外的所有不必要标记。我如何处理链接呢?如果有更好的方法,请告诉我。

期望的结果:

This is the title. This is the subtitle. some text some more text. link here

这个行吗:https://dev59.com/4I7ea4cB1Zd3GeqPFcF3? - Vasil Dininski
7个回答

20

我想到了这个正则表达式:

(?:__|[*#])|\[(.*?)\]\(.*?\)

var str = '# This is the title. ## This is the subtitle. **some text** __some more text__. [link here](http://google.com)'

document.write(String(str).replace(/(?:__|[*#])|\[(.*?)\]\(.*?\)/gm, '$1'));


这匹配一个空链接:()[]... 这是期望的行为吗? - phillyslick
2
@BenPolinsky 如果需要的话,可以将其更改为 (?:__|[*#])|\[(.+?)\]\(.+?\),但空链接也是一种链接样式,不是吗? :p - Thomas Ayoub
6
这似乎也符合Markdown的标题标签##和加粗标签** - PJATX
1
我会为链接添加第二个组:(?:__|[*#])|\[(.+?)]\((.+?)\) - dominik
1
它匹配字面上的 #*,它们与 Markdown 链接无关。 - Wasi Master
显示剩余2条评论

9
接受的答案匹配加粗标签 * 和标题 ###。如果在一行上有多个方括号对,则Marvin的修复程序匹配奇怪的文本组 (例如[word] a [link](url))。 这个正则表达式可以解决这个问题:
.replace(/\[([^\[\]]*)\]\((.*?)\)/gm, '$1')

注意,带有括号对的URL需要进行URL编码。


1
这个正则表达式在 [aaaa[bbb]dd](some-url) 中失败了。 - ylc395

4

Thomas的回答可以匹配标题(###)和粗体标签(*)。如果要避免匹配它们,请改用以下正则表达式:

.replace(/([])|\[(.*?)\]\(.*?\)/gm, '$1')

对于使用JavaScript/Node匹配Markdown链接模式的人可能会很有用。


1

使用简单的正则表达式来正确处理Markdown太过复杂。考虑以下示例:

[`[test](test)`](test)
[\[](test) [\]](test)
`[test` [test](test) `test](test)`
``test`[test`` [test](test) ``test`](test)``

在Markdown中,字符的含义取决于它们出现的上下文。正如您所看到的,即使是StackOverflow的语法高亮也很难正确解释最后一行。此外,Markdown编译器通常允许在文本中使用原始HTML。
如果您想要一个简单的解决方案,请编译Markdown并剥离所有HTML元素。
function getMarkdownText(markdown) {
    const compiled = sanitize(marked(markdown));
    const el = document.createElement("div");
    el.innerHTML = compiled;
    return el.innerText;
}

如果您想要一个运行速度更快但实现更复杂的解决方案,可以自己钩入 Markdown 编译器并使其生成所需的输出。

1

对我而言,这是工作。

string.match(/\[[^\]]*\]\([^)]*\)*/)

1

这个正则表达式可以匹配遵循[一些参考文本](一些url)模式的markdown文本,并包含两个组,分别包含参考文本和url的值。

\[([^\]]+)\]\(([^)]+)\)

如果需要,您可以直接将原始字符串中的markdown文本替换为参考文本。


0

试试这个:

function stripMarkdown(text) {
  var str = String(text).replace(/__|\*|\#|(?:\[([^\]]*)\]\([^)]*\))/gm, '$1');
  return str;
}

var testStr = '# This is the title. ## This is the subtitle. **some text** __some more text__. [link here](http://google.com)'

document.write(stripMarkdown(testStr));

它用第一个捕获组替换匹配项,即链接的文本。如果匹配项不是链接(Markdown),则为空。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接