简体   繁体   中英

Javascript regex to matched group

I have a multiline log file that I am attempting to parse with a regex and javascript into something more readable, I have used this question as a reference but am getting unexpected results Javascript replace with reference to matched group? .

Basically b logs "first time" undefined "second time" where I would expect to see the file name as the second match.

Here is a sample of the regex and data string that I am trying to match which results in matches. http://regex101.com/r/bW9xD4

I am trying to order the matches so that the filename is first, followed by the first time matched followed by the second time matched, can anyone point me in the right direction?

Code

var VIRTUAL = (function() {
  // Module globals
  var $ = {}; 

  // Module methods
  $ = {
    compareDelivery : function( data ) {
      var regex = new RegExp( '(\\d{2}:\\d{2}:\\d{2})|([0-9a-z]+.xml)', 'gmi' ), out = [];

      var found = data.replace(regex, function ( a, b, c ) {
          console.log(a);  

      });

      return out;
    }

  };


  return $;

}());

JSBIN: http://jsbin.com/manej/3/edit?js,console,output

By looking at your data, maybe you could use a pattern like this instead

"(Time .*?)\\s(Filename .*?)\\s(Generated [^\\n]*)"

and the replaceor

function ($0, time1, file, time2) {
    // .. do stuff
}

Your current method isn't working because each match is independent to the previous one; the only reason it finds them is the g flag. The way I've suggested, the match finds all in the group at once and a g flag would make it work over multiple lines.

KryptoniteDove, this simple code will do it (see the output in the online demo ):

<script>
var subject = 'Time 2014-05-22T10:39:04.890117+01:00 Filename S140522DSS10002.xml::938c287eb522359b600f74bb3140bb64 Generated 2014-05-22T10:38:46.000000+01:00';
var regex = /Time.*?(\d{2}:\d{2}:\d{2}).*?([0-9a-z]*\.xml).*?(\d{2}:\d{2}:\d{2})/i;
var match = regex.exec(subject);
if (match != null) {
        document.write(match[2] + "<br>");
        document.write(match[1] + "<br>");
        document.write(match[3] + "<br>");
}
</script>

How does this work?

Instead of trying multiple matches, we match everything with a single regex, capturing the file name and the times in capture groups 1, 2 and 3.

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