\z PCRE equivalent in JavaScript regex to match all markdown list items

前端 未结 1 1555
小蘑菇
小蘑菇 2021-01-20 22:46

I\'m trying to parse a Markdown style list into HTML. I am using several Regular Expressions for this, all according to the JavaScript standard. I know there are se

相关标签:
1条回答
  • 2021-01-20 23:02

    If you want to match the very end of string position in a JavaScript regex that has a m flag you may use $(?![^]) or $(?![\s\S]) like pattern. Your pattern will look like

    /^(?:\d.|[*+-]) [^]*?(?=^(?:\d.|[*+-])|$(?![^]))/gm
                                           ^^^^^^^^ 
    

    See the regex demo. The $(?![^]) (or $(?![\s\S])) matches the end of a line that has no other char right after it (so, the very end of the string).

    However, you should think of unrolling the lazy dot part to make the pattern work more efficiently.

    Here is an example:

    /^(?:\d+\.|[*+-]) .*(?:\r?\n(?!(?:\d+\.|[*+-]) ).*)*/gm
    

    See the regex demo

    Details

    • ^ - start of a line
    • (?:\d+\.|[*+-]) - 1+ digits and a dot or a * / + / -
    • - a space
    • .* - any 0+ chars other than line break chars as many as possible
    • (?:\r?\n(?!(?:\d+\.|[*+-]) ).*)* - 0 or more sequences of a CRLF or an LF line ending not followed with - 1+ digits and a dot or a * / + / - followed with a space and then the rest of the line.
    0 讨论(0)
提交回复
热议问题