Reputation: 765
I have markdown
like below:
# Heading!
* unorder list!
1. ordered list
*no it's not list
2.just normal text
```
block
code
python
```
#goodbye
And I want use regex to seperate it to 3 part
, first and last is normal text, second is code block
Like this (some newlines is dropped by stackoverflow) :
First:
# Heading!
* unorder list!
1. ordered list
*no it's not list
2.just normal text
Code block:
```
block
code
python
```
Last:
#goodbye
I have used
/^```(.|\n)+```$|^(.|\n)+(?!`)$/gm
in javascript
but not working. Can't get the code block.
Anyone have ideas?
Upvotes: 1
Views: 55
Reputation: 626802
You may use a regex to match 3 backticks at the start of the line and then any chars, as few as possible, up to the first line that starts with 3 backticks, and wrap the whole pattern with a capturing group to use in split
so that the matched part also landed in the resulting array:
s.split(/^(`{3}[^]*?^`{3})/m)
The pattern matches:
^
- start of a line`{3}
- 3 backticks[^]*?
- any 0+ chars, as few as possible^
- start of a line`{3}
- 3 backticks.JS demo:
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));
Upvotes: 1
Reputation: 176
With the option 'm' your regex is executed line by line. You'll need to test with one quest and manage the line breaks.
Like it:
(?:\s|\S)([\s\S]+.*)
See: https://regex101.com/r/Re23vd/1
Upvotes: 0
Reputation: 91385
Why not split on ``` ?
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);
Upvotes: 0