re = /(?:^|\n)##\s[^\n]*\n+(.*?)(?=\n##?\s|$)/
str = '# This is an H1
content
content
content
## This is an H2 that ends in another H2
matched content 1
matched content 1
matched content 1
## This is an H2 that ends in an H1
matched content 2
matched content 2
matched content 2
# This is an H1, it\'s content doesn\'t belong to any H2
content
content
content
## This is an H2 that goes on until the end of the file
matched content 3
matched content 3
### This H3 belongs to the H2 above
matched content 4
matched content 4'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html