Parse Markdown that is separated by `#` with regex pattern

Viewed 210

I'd like to parse Markdown that is separated by # (single hash). I've been try to that with Ruby.

Below code outputs ["# Bob's markdown header 1\n\nsomething here.\n\n", "#", "# kitty's header 1\n\nmeow.\n\n"]

p \
arrayobj = <<-EOS.scan(/^#[^#]*/m)

# Bob's markdown header 1

something here.

## this is markdown header 2

yeah.

# kitty's header 1

meow.

EOS

However what I wanted is below.

["# Bob's markdown header 1\n\nsomething here.\n\n## this is markdown header 2\n\nyeah.\n\n", "# kitty's header 1\n\nmeow.\n\n"]

In that case, how do you parse the Markdown?

1 Answers

You may match a line starting with # not followed with another # and any amount of subsequent lines that do not start with such a standalone # char:

.scan(/^#(?!#).*(?:\R(?!#(?!#)).*)*/)

See the Ruby demo online.

Pattern details

  • ^ - start of a line
  • #(?!#) - a # not followed with #
  • .* - the rest of the line
  • (?:\R(?!#(?!#)).*)* - zero or more consecutive occurrences of:
    • \R(?!#(?!#)) - any line break sequence (use \n for old Ruby versions) that is not followed with a standalone #
    • .* - the rest of the line.
Related