Beh01der / node-grok

Regular expression template library for Node.js inspired by logstash grok filter module
ISC License
51 stars 32 forks source link

Get pattern position with grok #26

Open jgsqware opened 5 years ago

jgsqware commented 5 years ago

Hi, is it possible with grok to have the start position of each pattern, to be able to highlight only some portion of string for example?

pchakour commented 4 years ago

It's possible by patching the code.

You have to patch the index.js file. Find the parseSync method and replace it by the following :

function(str) {
        if (!t.regexp) {
            t.regexp = new OnigRegExp(t.resolved);
        }

        var result = t.regexp.searchSync(str);

        if(!result)
            return null;

        var r = {};

        result.forEach(function(item, index) {
            var field = t.fields[index];
            if(field && item.match) {
                r[field] = item;
            }
        });

        return r;
    };

It will return for each key an object lik this:

{ index: 78, start: 41, end: 44, length: 3, match: 'GET' }

where start is the start position, end the end position and match the matched value.