用于 Markdown 中代码防护的 JavaScript 正则表达式

发布于 2024-12-18 21:04:06 字数 364 浏览 5 评论 0原文

我正在尝试在 showdown.js 中添加对代码防护的支持,但我对正则表达式仍然是个菜鸟。如果您不知道,代码防护就像这样:

```javascript
alert('hello world');
```

然后它会创建类似的内容:

<div class="highlight">
  <pre lang="javascript">
    alert('hello world');
  </pre>
</div>

如何在 JavaScript 风格的正则表达式中捕获 ```(anything)\n(anything)``` ?

I'm trying to add support into showdown.js for code fencing, but I'm still sort of a noob at regex. Code fencing, if you don't know, is like this:

```javascript
alert('hello world');
```

Then it'd create something like:

<div class="highlight">
  <pre lang="javascript">
    alert('hello world');
  </pre>
</div>

How do I go about capturing ```(anything)\n(anything)``` in JavaScript flavored regex?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

峩卟喜欢 2024-12-25 21:04:06
r = /`{3}(?:(.*$)\n)?([\s\S]*)`{3}/m;
r.exec(yourSampleString); // => [..., "javascript", "alert('hello world');\n"]
r.exec('```puts "ok"```'); // => [..., undefined, "puts \"ok\""]
r.exec('```foo```bar```'); // => [..., undefined, "foo```bar"]
r = /`{3}(?:(.*$)\n)?([\s\S]*)`{3}/m;
r.exec(yourSampleString); // => [..., "javascript", "alert('hello world');\n"]
r.exec('```puts "ok"```'); // => [..., undefined, "puts \"ok\""]
r.exec('```foo```bar```'); // => [..., undefined, "foo```bar"]
握住我的手 2024-12-25 21:04:06

这将得到一个包含所有内容的数组

```

result = subject.match(/`{3}[\s\S]*?`{3}/g);

但是要注意嵌套:

```

会很麻烦..

This will get an array of everything between

```

result = subject.match(/`{3}[\s\S]*?`{3}/g);

But beware that nested:

```

will be trouble..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文