Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove YAML header from markdown file

How to remove a YAML header like this one from a text file in Ruby:

---
date: 2013-02-02 11:22:33
title: "Some Title"
Foo: Bar
...

---

(The YAML is surrounded by three dashes (-))

I tried

text.gsub(/---(.*)---/, '') # text is the variable which contains the full text of the file

but it didn't work.

like image 509
musicmatze Avatar asked Dec 05 '22 12:12

musicmatze


2 Answers

The solution mentioned above will match from the first occurrence of --- to the last occurrence of --- and everything in between. That means if --- appears later on in your file you'll strip out not only the header, but some of the rest of the content.

This regex will only remove the yaml header:

/\A---(.|\n)*?---/

The \A ensures that it starts matching against the very first instance of --- and the ? makes the * be non-greedy, which makes it stop matching at the second instance of ---.

like image 195
Jeremy Green Avatar answered Dec 22 '22 07:12

Jeremy Green


Found a solution, regex should be:

/---(.|\n)*---/
like image 23
musicmatze Avatar answered Dec 22 '22 07:12

musicmatze