Node.js: Regular Expression To Get “From: ” and “To: ”

后端 未结 2 1688
被撕碎了的回忆
被撕碎了的回忆 2021-02-14 08:11

Given this text file:

Received: from unknown (HELO aws-bacon-delivery-svc-iad-1007.vdc.g.com) ([10.146.157.151])
  by na-mm-outgoing-6102-bacon.iad6.g.com with E         


        
2条回答
  •  梦毁少年i
    2021-02-14 08:51

    This question was just suggested to me (even though it's quite old!?) and I think the accepted answer doesn't exactly do what was asked for (get every field + body), so I thought I'll share this...

    To get each header and its value there is a quite simple regex (http://regexr.com/3e60k) with two capture groups, that also allows line breaks within a value (if indented):

    var pattern = /(.+):\s(.+(?:\n +)?.+)?/g;
    

    The pairs can be retrieved like

    var match;
    while (match = pattern.exec(string)) {
        console.log(match[1] + ": " match[2]);
    }
    

    It's even simpler to get the body (http://regexr.com/3e60h), because it has to be separated from the headers with two new-line characters:

    var body = string.match(/\n\n([\s\S]+)/)[1];
    

    That matches anything after the two \n (whitespace and non-whitespace).

    See this fiddle for a complete example: http://es6fiddle.net/issocwc9/

提交回复
热议问题