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

后端 未结 2 1694
被撕碎了的回忆
被撕碎了的回忆 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条回答
  • 2021-02-14 08:45

    Try this:

    Code:

    //var rePattern = new RegExp(/^Received:(.*)$/);
    var rePattern = new RegExp(/^Subject:(.*)$/);
    
    var arrMatches = strText.match(rePattern);
    

    Result:

    arrMatches[0] -> Subject: test
    arrMatches[1] -> test
    
    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题