Note that there are some explanatory texts on larger screens.

plurals
  1. POjavascript regular expression match only returning last match
    text
    copied!<p>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.</p> <p>Thanks for taking a look...</p> <p>Now the <strong>CODE</strong> </p> <p>Also available for experimentation here in a <a href="http://c9.io/janarde/bs-parser" rel="nofollow">cloud 9</a> ide.</p> <pre><code>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; </code></pre> <p>And a test file:</p> <pre><code>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 &lt; data.length; i++) util.log(data[i]); }); </code></pre> <p>Here is the <a href="https://www.debuggex.com/r/ipV0qlHjdW4PYuhp/0" rel="nofollow">debuggex</a> for the regular expression.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload