简体   繁体   中英

javascript regular expression match only returning last match

I have a small node application that takes some input, applies a regular expression to extract some info and should return an array of matches. All of it it pretty straight forward but the behavior I am seeing is not expected. My understanding was that if I have input with multiple lines that match this regex then each line would be an element in the array that the match returns. Unfortunately it looks like the array only contains the match groups for the last line. Is there a way to rewrite this, without iterating through the input twice, so that I can populate a nested array with the matched data per line? It would be great to return the match groups as elements, but I need to do this for each line. The end goal is to turn all this into formatted JSON for a downstream application.

Thanks for taking a look...

Now the CODE

Also available for experimentation here in a cloud 9 ide.

var util = require('util');

var re = /(processed)(.*?)\((.*?)\)(.*?)([0-9]\.[0-9]+[0-9])/g;
var data;
var returnData = [];
var Parser = function(input) {
    util.log("Instantiating Parser");

    this.data = input;
};

Parser.prototype.parse = function(callback) {
    util.log("In the parser");

    this.returnData = re.exec(this.data);
    callback(this.returnData);
}

exports.Parser = Parser;

And a test file:

var Parser = require("./parser.js").Parser;
var util = require('util');
var fs = require('fs');

var data = "worker[0] processed packet (0x2000000, 1200358, t) in 0.000021 seconds\n" +
"worker[0] processed packet (0x2000000, 400115, b) in 0.000030 seconds\n"+
" (0) Registration Stats: (1387305947, 0x3d00000a, 17024, 2504, 0, 400109, 400116, b)\n"+
"worker[0] processed packet (0x1000000, 400116, b) in 0.000045 seconds\n"+
"worker[0] processed packet (0x1000000, 1200369, t) in 0.000024 seconds\n";

util.log("creating new parser");
var Parser = new Parser(data);

util.log("calling parse");
Parser.parse(function(data) {
        for (var i=0; i < data.length; i++)
            util.log(data[i]);
});

Here is the debuggex for the regular expression.

re.exec only returns one match each time it is executed. If you want an array of all the matches, you need to do something like this:

var matchedData = [];
var match;
while (match = re.exec(this.data)) {
    matchedData.push(match);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM