REGEX - JavaScript / Blockly

201 views Asked by At

I have two (or more) different export from our system in raw data. I would like to separete it by using regex without using IF foreach case.

Bellow are two examples:

  1. <14>Apr 29 10:00:00 nimble1-A NMBL: Array:nimblegroup Type:14883 Time:Fri Apr 29 10:00:00 2022#012 Id:8234 Target:nimble2-nimble1 Version:6.0.0.300-956221-opt Message:Successfully created a snapshot of the volumes associated with volume collection nimble2-nimble1 schedule test on synchronous replication partners pool-nimble2 and pool-nimble1.
  2. <14>May 1 00:53:01 nimble1-A NMBL: Group:nimblegroup Type:1016 Time:Sun May 1 00:53:01 2022#012 Id:9106 Object Id:- Object: Access Type:su Client IP:Console Status:Succeeded Version:6.0.0.300-956221-opt Message:Elevating user privilege to admin

In the first log I need to get only the Message. But in the othercase I need to get Object, Type, Client IP, Status, Message.

I expect that I need to use ? in regex, but I dont know how without using IF for every case.

Blockly image example here.

Thank you, for your help.

1

There are 1 answers

3
Stefan Jelner On

If i understand you right, you have above entries as strings.

With one single regular expression, it will be hard to do that. I personally would prefer a mix of a regular expression and split() and try to make a regular object out of it first.

Something like:

var entriesRaw = [
    '<14>Apr 29 10:00:00 nimble1-A NMBL: Array:nimblegroup Type:14883 Time:Fri Apr 29 10:00:00 2022#012 Id:8234 Target:nimble2-nimble1 Version:6.0.0.300-956221-opt Message:Successfully created a snapshot of the volumes associated with volume collection nimble2-nimble1 schedule test on synchronous replication partners pool-nimble2 and pool-nimble1.',
    '<14>May 1 00:53:01 nimble1-A NMBL: Group:nimblegroup Type:1016 Time:Sun May 1 00:53:01 2022#012 Id:9106 Object Id:- Object: Access Type:su Client IP:Console Status:Succeeded Version:6.0.0.300-956221-opt Message:Elevating user privilege to admin'
];

var entries = entriesRaw.map(function(entry) {
    return entry.split(/((?:Array|Client IP|Group|Id|Message|Object(?: Id)?|Status|Target|Time|Type|Version):)/g).reduce((acc, chunk, i, chunks) => {
        if(chunk.slice(-1) === ':' && i < chunks.length - 1) {
            var tmp = {};
            tmp[chunk.slice(0, -1)] = chunks[i + 1].trim();
            
            return Object.assign({}, acc, tmp);
        }
        
        return acc;
    }, {});
});

console.log(entries);

This way you have all of entries parsed into an array of objects with key-value pairs and you can access them.

The trick is to do backtracking inside of the split(), because this way the split chunks are part of the resulting array.

The problem with your entries is, that their syntax is hard to parse, so you have to come up with each key as a literal string in the regular expression.

If you need additional help, feel free to ask. :-)