多行正则表达式匹配,否定前瞻问题(CLOSED)

时间:2017-09-13 14:06:38

标签: javascript regex

我有markdown如下:

# Heading!
* unorder list!
1. ordered list
*no it's not list
2.just normal text

``` 
block 
code 
python
```

#goodbye

我希望使用正则表达式将其分隔为3 part,第一个和最后一个是普通文本,第二个是代码块

像这样(stackoverflow删除了一些换行符):

首先:

# Heading!
* unorder list!
1. ordered list
*no it's not list
2.just normal text

代码块:

```
block
code
python
```

最后:

#goodbye

我用过

/^```(.|\n)+```$|^(.|\n)+(?!`)$/gm
javascript

但没有工作。无法获取代码块。

有人有想法吗?

3 个答案:

答案 0 :(得分:1)

您可以使用正则表达式来匹配行开头的3个反引号,然后匹配尽可能少的任何字符,直到以3个反引号开头的第一行,并使用捕获组包装整个模式以使用在split中,以便匹配的部分也落在结果数组中:

s.split(/^(`{3}[^]*?^`{3})/m)

模式匹配:

  • ^ - 开始行
  • `{3} - 3次反击
  • [^]*? - 任意0个字符,尽可能少
  • ^ - 开始行
  • `{3} - 3个反击。

JS演示:

const regex = /^(`{3}[^]*?^`{3})/m;
const str = `# Heading!
* unorder list!
1. ordered list
*no it's not list
2.just normal text

\`\`\` 
block 
code 
python
\`\`\`

#goodbye`;
console.log(str.split(regex));

答案 1 :(得分:0)

为什么不拆分```?



var str = `# Heading!
* unorder list!
1. ordered list
*no it's not list
2.just normal text

\`\`\` 
block 
code 
python
\`\`\`

#goodbye`;

out = str.split('```');
console.log(out);




答案 2 :(得分:0)

使用选项'm',您的正则表达式将逐行执行。您需要使用一个任务进行测试并管理换行符。

喜欢它: (?:\s|\S)([\s\S]+.*)

请参阅:https://regex101.com/r/Re23vd/1