JavaScript regex无法正确查找和替换markdown代码块

7hiiyaii  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(83)

我已经通过gitbook-plugin-mermaid-gb3Gitbook安装了一个mermaid插件,这个插件可以通过markdown代码块标记解析代码并将其转换为svg文件,代码块如下所示:

```mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;

但是当我使用它的时候,我发现有些代码不能正常工作,经过检查,我发现这是插件内部的一个bug。
代码来自[**index.js**](https://github.com/chriswessels/gitbook-plugin-mermaid-gb3/blob/master/index.js)和下面列出的相关解析代码:

var mermaidRegex = /^mermaid((.*[\r\n]+)+?)?$/im;

function processMermaidBlockList(page) {

var match;

while ((match = mermaidRegex.exec(page.content))) {
var rawBlock = match[0];
var mermaidContent = match[1];
page.content = page.content.replace(rawBlock, '' +
mermaidContent + '');
}

return page;
}


正则表达式为`/^```mermaid((.*[\r\n]+)+?)?```$/im`,但它只能找到以**``美人鱼**开头的代码块,如果前面或后面有空格,它将无法工作
我期待的是下面这样

-- valid

graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;

-- valid, there can be space between ``` and mermaid

graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;

-- valid, there can be space before or after ```

graph TD;
 A-->B;
 A-->C;
 B-->D;
 C-->D;

--invalid, there can not be have extra characters before abcmermaid
graph TD;
A-->B;
A-->C;
B-->D;
C-->D;


--invalid, there can not be have extra characters before ```
abc ```mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;

--invalid, there can not be have extra characters before abcmermaid
graph TD;
A-->B;
A-->C;
B-->D;
C-->D;


--invalid, there can not be have extra characters after ```
```mermaid
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
```  abc

--invalid, there can not be have extra characters after mermaid
```mermaid abc
graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;

我把`/^```mermaid((.*[\r\n]+)+?)?```$/im`改成了`https://regex101.com/r/CIrooL/1`,并通过[**https://regex101.com/r/CIrooL/1**](https://regex101.com/r/CIrooL/1)测试了一下,看起来还可以,但在JavaScript中不工作,我不知道为什么。

// this line will be blocked using the updated regex
while ((match = mermaidRegex.exec(page.content))) {
}


有人能帮帮我吗?提前感谢!
ddarikpa

ddarikpa1#

而不是匹配所有这些块和“原始”替换每个块的想法是只做一个 * 全局 * 替换。同时根据需要修改正则表达式like this (regex101)

const mermaidRegex = /^[ \t]*```\s*mermaid[ \t]*$([^`]*(?:`[^`]+)*)```$/igm;
  • 全局标志g用于替换每次出现
  • m多行标志用于使^匹配 line-start和$ line-end
  • [ \t]*将匹配any amount的空格或制表符
  • ([^](?:[^]+))` captures与 * 第一组 * 相关的部分。

被求反的类匹配除反引号以外的任何字符。
为了允许单次出现反引号,使用了重复组。
最后,改变你的功能:

function processMermaidBlockList(page) {
  page.content = page.content.replace(mermaidRegex, '<div class="mermaid">$1</div>');
  return page;
}

这里是一个JS演示在tio.run-$1在替换包含what's captured的 * 第一组 *。

相关问题