开发者

Node.js: Regular Expression To Delete Entire Line

开发者 https://www.devze.com 2023-02-24 19:56 出处:网络
How do I match the entire line starting with MTA: ? If I use: console.log(result[2].split(\"Reporting-MTA:\"))

How do I match the entire line starting with MTA: ?

If I use:

console.log(result[2].split("Reporting-MTA:"))

I will still get the rest of the line, I want to match the entire line starting with MTA:

Thanks

Edit:

I want to match the line so I can rea开发者_如何学JAVAd the lines BEFORE and AFTER that entire line. Now, I can only read the lines before and after the string "Reporting-MTA:"

Edit2:

2u+in.4eBZWuGLW.HROP9.bB7WHG
content-type: message/delivery-status

Reporting-MTA: dns; na-mm-outgoing-6102-bacon.iad6.com

Final-Recipient: rfc822;g
Action: failed
Status: 5.0.0 (permanent failure)
Diagnostic-Code: smtp; 5.1.2 - Bad destination host 'DNS Hard Error looking up tiagop.fdforg (MX):  NXDomain' (delivery attempts: 0)



/node/server.js:92
                console.log(r[1]);
               ^
TypeError: Cannot read property '1' of null

With this code:

console.log(result[2]);
        var r = result[2].match(/(.*)\r\nReporting-MTA\r\n(.*)/)
        console.log(r[1]);


If your input is from a text file then you need to look for the line breaks, so something like this...

It aint pretty but..

Test:

http://jsfiddle.net/wBR73/2/


Code:

var re = new RegExp(/((?:[\n\r]|.)*)(Reporting-MTA.*)((?:[\n\r]|.)*)/);
var arrMatches = strText.match(re);

Result:

arrMatches [1]   // Lines before a line Reporting-MTA:..$
arrMatches [2]   // Line started from Reporting-MTA:
arrMatches [3]   // Other lines after a line started from Reporting-MTA:


You can use match to do regular expression match and return an array of results to matches. This regex matches a pattern that starts (^) with MTA: and is followed by anything (.) zero or more times (*)...

var matches = result[2].match(/^MTA:.*/)
console.log(matches[0])

to capture groups within the match you can use brackets...

var matches = result[2].match(/^(MTA:)(.*)/)
console.log(matches[0]) // whole matched string
console.log(matches[1]) // first bracketed group - 'MTA:' in this case
console.log(matches[2]) // second bracketed group - the rest of the string in this case


Maybe it is easier to replace the line(s) you don't want

var replaced = result[2].replace(/.*Reporting-MTA:.*/gm,'')
console.log(replaced)
0

精彩评论

暂无评论...
验证码 换一张
取 消