Python Regex to match YAML Front Matter

后端 未结 2 1165
小蘑菇
小蘑菇 2021-02-04 19:40

I\'m having trouble crafting a regex to match YAML Front Matter

This is the front matter I was trying to match:

    ---
    name: me
    title: test
             


        
2条回答
  •  暖寄归人
    2021-02-04 20:44

    To unpack what you are currently doing with this regular expression:

    r'^(---)(.*)(---)$':

    • r: Treat this as a string literal in Python
    • ^: Start the evaluation at the beginning of a line
    • (---): Parse --- into an anonymous capture group
    • (.*): Parse all characters (.) non-greedily (*) until the next expression
    • (---): As above
    • $: End at the evaluation of the end of a line

    The trouble is this will fail when whitespace is present. You're literally saying: find dashes that occur at the beginning of a line and parse until we find dashes that occur at the end of one. Furthermore, you're creating groups that I believe are not necessary to the useful evaluation of your regular expression, by using parentheses () around the dashes used to find YAML front matter.

    A better expression would be:

    r'^\s*---(.*)---\s*$'

    Which adds the repeating group \s* to capture whitespace characters between the beginning of the first line up to the dashes, adds this again between the second group of dashes to the end of that line, and captures everything between into a single anonymous capture group that you can then use for additional processing. If extracting the contents of the front matter isn't desired, simply replace (.*) with .*.

    Consider re.findall for multiple evaluations of this regular expression in a single file, and as mentioned, use re.DOTALL to allow the dot character to match new lines.

提交回复
热议问题