Search code examples
javascriptregexqregularexpression

how to match markdown block code between 3 grave accent


  • i know that this a common question but i searched a lot and not found what i need to
  • i'm trying to create simple markdown plug but i can't match the block code i tried this regex /(^\`{3}[\w|\W]+\`{3})/gm but it's get me every thing between the first and last grave accent and if there's anothe block code it's add them all inside one
  • for example the following string
 ``` 
  block code 
  word1
  word2
 ```

word without grave accent and it is will match it too

 ```
  another block code
  word1
  word2
  - it's will match it as part of the first block code
 ```

"""
some text after the grave accent text
word1
word2
"""`
  • this regex result is like the following array
0: "``` \nblock code\nword1\nword2\n```\n\nword without grave accent and it's will match it too\n\n```\nanother block code\nword1\nword2\n- it's will match it as part of the first block code\n```"
length: 1
  • and i want it to match then like this
0: "``` \nblock code\nword1\nword2\n```"
1: "```\nanother block code\nword1\nword2\n- it's will match it as part of the first block code\n```"
length: 2
  • I'm not good enough at regex so i hope someone help me

Solution

  • You'll want to lazily match your + quantifier: (\`{3}[\w|\W]+?\`{3})
    The +? will try to match one or more times with as few characters as possible, ensuring it doesn't greedily take up everything between your \`{3}s. Quantifiers are greedy by default.

    regex101 example

    Here's some more reading on lazy vs greedy.