Sakib Sakib - 1 year ago 46
Javascript Question

Javascript Regex to split line of log

I have a log like

t=2016-08-03T18:47:26+0000 lvl=dbug msg="Event Received" Service=SomeService

and I want to turn it into a javascript object like

t: 2016-08-03T18:47:26+0000,
lvl: dbug
msg: "Event Received"
Service: SomeService

But I am having trouble coming up with a regex that will detect the string "Event Received" in the log line.
I want to split the log line by space but because of the string it is much more difficult.

I am trying to come up with a regex that will detect the fields and parameters so that I can isolate them and split with the equal sign.

Answer Source

I suggest a regex without any lookahead:

var re = /(\w+)=(?:"([^"]*)"|(\S*))/g; 

See the regex demo

The point is that the first group ((\w+)) captures the attribute name and the 2nd and 3rd are placed into a non-capturing "container" as alternative branches. Their values can be checked and then either one will be used to fill out the object.

Pattern details:

  • (\w+) - Group 1 (attribute name) matching 1+ word chars (from [a-zA-Z0-9_] ranges)
  • = - an equal sign
  • (?:"([^"]*)"|(\S*)) - a non-capturing "container" group matching either of the two alternatives:
    • "([^"]*)" - a quote, then Group 2 capturing 0+ chars other than ", and a quote
    • | - or
    • (\S*) - Group 3 capturing 0+ non-whitespace symbols.

var rx = /(\w+)=(?:"([^"]*)"|(\S*))/g;
var s = "t=2016-08-03T18:47:26+0000 lvl=dbug msg=\"Event Received\" Service=SomeService";
var obj = {};

while((m=rx.exec(s))!==null) {
 if (m[2]) {
     obj[m[1]] = m[2];
 } else {
     obj[m[1]] = m[3];