Ahmed Enzea
Ahmed Enzea

Reputation: 55

Javascript regex match formatting to parse data

I need to match data within a string in order to parse the data. The format for the data is follows

A*(anything)B*(anything)ABC*(anything)

The keys will always be A, B, ABC or DCE.

I have it working for the keys with the length of one character.

$(function() {

var s = "A*(anything)B*(anything)ABC*(anything)DCE*(anything)";

s.match(/(A|B|ABC|DCE)\*[^*]+(?!\*)/g).forEach(match => {
    var [k, v] = match.split('*');

    console.log(k + "->" + v);
});

});

However, this is the output (doesn't work with 1+ length keys

A->(anything)
B->(anything)AB
DCE->(anything)

The value is not always (anything) - it is dynamic.

I think the issue is with (?!*)/g

Upvotes: 0

Views: 58

Answers (2)

ewwink
ewwink

Reputation: 19154

why not using [^\)] instead of [^*]

var s = "A*(anything)B*(anything)ABC*(anything)DCE*(anything)";

// s.match(/[ABCDE]+\*[^\)]+\)/g).forEach(match =>
// or
s.match(/(A|B|ABC|DCE)\*[^\)]+\)/g).forEach(match => {
    var [k, v] = match.split('*');

    console.log(k + "->" + v);
});

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522254

I managed to get your logic working using a formal regex matcher. The problem with your regex pattern is that you are using a negative lookahead to stop the match. Instead, use a positive lookahead which asserts that we have reached the next (A|B|ABC|DCE)* or the end of the string.

var s = "A*(anything)B*(anything)ABC*(anything)DCE*(anything)";
var regexp = /(A|B|ABC|DCE)\*(.*?)(?=(?:A|B|ABC|DCE)\*|$)/g;
var match = regexp.exec(s);
while (match != null) {
    print(match[0].split("\*")[0] + "->"+ match[0].split("\*")[1]);
    match = myRegexp.exec(myString);
}

Demo

Upvotes: 1

Related Questions