KryptoniteDove
KryptoniteDove

Reputation: 1268

Regex is stopping at first match in loop

I have a regex shown below and a while loop to iterate over the data, however the regex stops after the first match and I would like it to continue until no more can be found.

I have global and multiline set. Does anyone have any ideas? I'm at a loss!

This bin http://jsbin.com/manej/8/edit?js,console,output illustrates the behaviour of the below code that will return Filename Last Time, First Time. Any assistance would be massively appreciated!

var regex = new RegExp( '(\\d{2}:\\d{2}:\\d{2}).*?([0-9a-z]+\\.xml).*?(\\d{2}:\\d{2}:\\d{2})', 'gmi' ), out = [];

      while ( ( match = regex.exec( data ) ) !== null ) {

        out.push(match[2], match[3], match[1]);  
          return out;  
      }

var data is: -

Time 2014-05-22T10:39:04.890117+01:00 Filename S140522DSS10002.xml::938c287eb522359b600f74bb3140bb64 Generated 2014-05-22T10:38:46.000000+01:00 Time 2014-05-22T10:39:04.890117+01:00 Filename S140522DSS10001.xml::d525814afc7f9c92e7709d9a2ec46803 Generated 2014-05-22T10:38:31.000000+01:00 Time 2014-05-22T10:39:33.908891+01:00 Filename S140522DSS10005.xml::54df47de51346319d5064ed5c380ace1 Generated 2014-05-22T10:39:11.000000+01:00 Time 2014-05-22T10:39:33.908891+01:00 Filename S140522DSS10004.xml::a109662fad39b9a9ada2d8d5968c55ed Generated 2014-05-22T10:39:09.000000+01:00 Time 2014-05-22T10:39:33.908891+01:00 Filename S140522DSS10003.xml::0a15d6558032cdfdd3cab2ca4a723694 Generated 2014-05-22T10:39:03.000000+01:00 Time 2014-05-22T10:40:03.896013+01:00 Filename R140522DSS10001.xml::ffd98e7e99625a957370f4ed03de8612 Generated 2014-05-22T10:39:55.000000+01:00 Time 2014-05-22T10:42:33.896617+01:00 Filename S140522DDG10001.xml::d7010a49dd39731ef05e1452314a84d1 Generated 2014-05-22T10:42:21.000000+01:00 Time 2014-05-22T10:43:03.899967+01:00 Filename S140522DDG10002.xml::7297c9e66cd418eabee94cba8a464df7 Generated 2014-05-22T10:42:36.000000+01:00 Time 2014-05-22T10:43:03.899967+01:00 Filename S140522DDG10003.xml::e4e1071794e586bf10350dcb073d0662 Generated 2014-05-22T10:42:53.000000+01:00 Time 2014-05-22T10:43:34.196675+01:00 Filename S140522DDG10004.xml::b520bc560e0d117520620d782c0e9ce0 Generated 2014-05-22T10:42:59.000000+01:00

Upvotes: 0

Views: 169

Answers (2)

aelor
aelor

Reputation: 11116

The return statement should be outside the loop:

var regex = new RegExp( '(\\d{2}:\\d{2}:\\d{2}).*?([0-9a-z]+\\.xml).*?(\\d{2}:\\d{2}:\\d{2})', 'gmi' ), out = [];

while ( ( match = regex.exec( data ) ) !== null ) {
    out.push(match[2], match[3], match[1]);  
}

return out;  

Upvotes: 2

neerajdngl
neerajdngl

Reputation: 200

Use return outside of while loop

var regex = new RegExp( '(\\d{2}:\\d{2}:\\d{2}).*?([0-9a-z]+\\.xml).*?(\\d{2}:\\d{2}:\\d{2})', 'gmi' ), out = [];

      while ( ( match = regex.exec( data ) ) !== null ) {

        out.push(match[2], match[3], match[1]);  

      }
return out;  

Upvotes: 1

Related Questions