Search code examples
regexmarkdown

Regex to match line breaks only on lines with text that do not precede an empty line?


I am trying to replace line breaks in markdown files of poetry with markdown line breaks, which means adding two spaces to the ends of lines that a) have text and b) do not precede an empty line.

So, the following text:

this line should have a break
and this one
but not this one

and this one should
and this one
but not this one

and so on

Would have two space added where the X appears:

this line should have a breakX
and this oneX
but not this one

and this one shouldX
and this oneX
but not this one

and so on

I cannot seem to find the correct incantation with my muddling. The closest I came up with is (.*?)\n(?!\n) but it matches the empty lines too.


Solution

  • You can check for a non white space \S before \n in the capture group:

    (.*\S)\n(?!\n)
    

    In the replacement insert the capture and space: $1 \n (regex101 demo)


    Or if lookbehind is supported, simply replace (?<!\s)\n(?!\n) with \n.